Spring_源代码解析——入门

Spring_源代码解析——入门

ID:83420714

大小:13.40 MB

页数:95页

时间:2023-07-14

上传者:灯火阑珊2019
Spring_源代码解析——入门_第1页
Spring_源代码解析——入门_第2页
Spring_源代码解析——入门_第3页
Spring_源代码解析——入门_第4页
Spring_源代码解析——入门_第5页
Spring_源代码解析——入门_第6页
Spring_源代码解析——入门_第7页
Spring_源代码解析——入门_第8页
Spring_源代码解析——入门_第9页
Spring_源代码解析——入门_第10页
资源描述:

《Spring_源代码解析——入门》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

ᙠRod.JohnsonḄீீProfessionalJavaDevelopmentwiththespringframeworkுுṹ⍝Ẉ᳝ᨵᐶ$Ḅ%&'()Ẇᔳ,ᙠSpring-IOC.ᘤḄ0⌕ᙢ3ᡃ56789:;SpringḄ<ᵨὅ?@IOC.ᘤA▭CDEFᕖHᡃ5IJ9BeanFactory6Dᡃ5ᑮḄloC.ᘤLᯠSpringNᡃ5OᜓQ8RloC.ᘤᩭ<ᵨT᪵IJVᡃ5W7%ḄX☢7%ḄZ3[7%Ḅ\]Ḅ^_`aᩭbcᡃ5◤⌕ḄloC.ᘤ஺ᙠSpring-ᨬghḄIOC.ᘤijDBeanFactory-TijNᐹlḄIOC.ᘤḄAmnᨬghḄopq^-7stFḼnNIOC.ᘤTvijwxy⌕z{|ᵨ}~Ḅᨬgh⌕Javaṹ1.publicinterfaceBeanFactory{2.3.஻TD:FactoryBeanḄ_^_N᝞<ᵨbeanḄFactoryBeanᑮḄ:DᔆᡂḄ:4.஻᝞◤⌕ᑮᔆh◤_5.StringFACTORY_BEAN_PREFIX=6.7.8.஻T᪷beanḄ,ᙠIOC.ᘤ-ᑮbeanA,TIOC.ᘤ6DᜧḄI.ᔆ஺9.ObjectgetBean(Stringname)throwsBeansException;10.11.஻T᪷beanḄClassᩭᑮbeanAC☢ḄV7%ᙠ;᝞᪷¡ḄbeanAḄClass◤⌕Ḅ7%Ḅ¢஺12.ObjectgetBean(Stringname,ClassrequiredType)throwsBeansException;13.14.஻T£¤:beanḄDᔲᙠIOC.ᘤᨵTḄbean15.booleancontainsBean(Stringname);16.17.஻T᪷beanᑮbeanA¦%§ᑨ©TbeanD7Dᓫ«18.booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;19.20.஻T:ᑮbeanAḄClass21.ClassgetType(Stringname)throwsNoSuchBeanDefinitionException;22.23.஻TᑮbeanḄ¬,᝞᪷¬,Fᐸ¯°ᩭ24.String[]getAliases(Stringname);25.26.}ᙠBeanFactory±:IOC.ᘤḄgh²Nn^_᪷h7ᐵ´wḄbeanDt᪵^_t᪵µ¶Ḅ-6·ᡃ5±ᐵ´WTᔆᡃ5ᑮᑮEF¸¹:º;ᔆDtF¸Tv:ḄTghḄij7ᐵ´Tv஺᝞⌕ᐵ´ᔆDt᪵¸:Ḅ|ᵨ}~◤⌕<ᵨᐹlḄIOC.ᘤAm-LᯠwIJ»¼᪷TBeanFactoryᩭAm»¼ḄIOC.ᘤ½T¾ᨵx⌕NSpring¿ÀNᡃ5OᜓÁÂᑡᔆᩭÄᡃ5<ᵨ஺Å᝞XmÆeanFactory6D┐:ᨬgẠḄBeanFactoryḄIOC.ᘤḄAm-

1TAm<ᵨxmlᩭ^_100.ᘤ-ḄbearioSpring£¤BeanFactoryḄghAm,XmÆeanFactory%᪵ḄÉÊ<ᵨËÌË]ᩭᑮ:I0C.ᘤḄ-AbstractBeanFactory,DefaultListableBeanFactoryTvNᐸ£¤ËÌÍÎ஺ᐸ-ÉÊresourceijᩭbean^_ᦪ:Xml^_ᦻ«ḄÑ᪆ÉÊÓᡲÕXmlBeanDefinitionReaderᩭÖᡂ஺×☢ᡃ5᪷ØCḄÙÚᓫḄÛÜI0C.ᘤḄÝbÊ}Javaṹ1.ClassPathResourceres=newClassPathResource("beans.xml");2.DefaultListableBeanFactoryfactory=newDefaultListableBeanFactory();3.XmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(factory);4.reader.loadBeanDefinitions(res);TvṹÛÜJ×Þßà1.ÝbI0Cá[ᦻ«ḄZ2.ÝbBeanFactory3.âã¡á[`aḄBeanDefinäonReader,TDXmlBeanDefinitionReaderá[ÕBeanFactory4.W^_ÁḄZ3[ãᐭá[`aᐹlḄÑ᪆Ê}ᵫXmÆeanDefinitionReaderᩭÖᡂT᪵Öᡂ᦮¶ᐭbean^_ḄÊ}஺ᡃ5ḄloC.ᘤ6bc'ᩭ஺ᙠBeanFactoryḄṹ-ᡃ5IJᑮJavaṹ1.publicclassXmlBeanFactoryextendsDefaultListableBeanFactory{2.஻TN.ᘤ^_è<ᵨḄbean^_ã¡ᘤ3.privatefinalXmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(this);4.publicXmlBeanFactory(Resourceresource)throwsBeansException{5.this(resource,null);6.}7.஻ᙠéêᓄìᦪ-<ᵨã¡ᘤᩭ:Zí²ã¡,ᑮbean^_`a஺8.publicXmlBeanFactory(Resourceresource,BeanFactoryparentBeanFactory)throwsBeansException{9.super(parentBeanFactory);10.this.reader.loadBeanDefinitions(resource);11.)ᡃ5ᙠî☢ᑮã¡ᘤã¡Zïðbean^_`aḄ᦮Ê}ghCDC×ᦻḄᜐᳮD᪵ḄWTᡃ5IJᑮC×ᦻXmÆeanFactoryTóRI0C.ᘤḄô¬BeanFactoryõõ7ᐹᜓ:Z^_Ḅpö?C×ᦻIJ»¼ÖᡂZ^_WT÷øCC×ᦻùÁᵨv஺úûᑖ᪆SpringBeanFactoryḄý᪀ᡃ5ᩭᙠBeanFactorygẠC᡽ḄApplicationcontext-ᡃᨬᵨḄᦻ஺◀ᐹᜓBeanFactoryḄᐰᦻᵨᑭ!*$%&ᢝ()Ḅ*+,ᡃ-.I/Applicationcontext᡽MessageSource*123,45ᙠ7ResourceLoader8ResourceḄ&ᢝ☢:᪵ᡃ$%<()ᙢ>?ᑮbeanAB3,*&ᢝᵨCDEFGHApplicationEventPublisher,:᪵ᙠᦻIJᐭCDLᑴNBeanFactoryOPᨵḄ஺ApplicationContextᐕᦻSᝅ-VWXᢝ᱄ᦻ$%Zᢝ[\ᦻ4]-:\4]ᡃᙠ%^7Web_ᘤIḄᦻa᛻Ḅᑖ᪆I$%efᙢ-ᑮ஺7gbeanḄhi$%ᙠ:\ᦻ4]Ijk✌ᐜnhopᦻᐸrO᱄ᦻ⌲tᔣ:᪵()ḄSpringᵨvw[\ᐳyḄbean

2ABa᛻஺:\ᡃᙠᑖ᪆Web_ᘤIḄᦻa᛻z{-ᑮ஺ApplicationcontextvwloC_ᘤḄ|⌕GHᙠᐸ4]Iᨵ~᝞AbstractApplicationContextᐹ4ḄBeanFactoryḄ5᝞FileSystemXmlApplicationContext8ClassPathXmlApplicationContextvw.ᦻḄ?◤⌕ᐵᐹ4Ḅ3,A2⚪஺oᵨṹᓄFileSystemXmlApplicationContextḄz᎛?.ijloC_ᘤḄ[ᐹ4⊤5-Applicationcontext,ÂᒹÄ᦮\BeanFactory°±ᓄḄW7gᱯAḄFileSystemXmÇeanFactory,ᡃ-ᑮA3,¾ᵫrefreshBeanFactory஺ᩭ5!

3ᙠAbstractXmlApplicationContextIAB7È,ḄÉÊWˤᵫXmÇeanDefirdtionReaderᩭÉÊ!Javaṹ1.protectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwslOException{2.//:ÌᵨXMLBeanDefinitionReaderᩭÍᐭbeanAB*+ḄXMLᦻD3.XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);4.5.஻:ÌξreaderḄa᛻ᐸIResourceLoaderOᡃᵨᩭAbeanAB*+3,¾.Ḅ6.஻/ÏᦻÐÑ5ResourceLoaderGHᡠ%$%Ó!GÔ.ᦻResourceLoaderÕ⌴XmlBeanDefinitionReader7.beanDefinitionReader.setResourceLoader(this);8.beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));9.10.initBeanDefinitionReader(beanDefinitionReader);11.஻:Ì×ᑮABØḄXmlBeanDefinitionReaderAbean*+ÙÚᜐᳮ12.loadBeanDefinitions(beanDefinitionReader);13.}×.ijbeanDefinitionReaderIÙÚᜐᳮ!Javaṹ1.protectedvoidloadBeanDefinitions(XmlBeanDefinitionReaderreader)throwsBeansException,lOException{2.Resource!]configResources=getConfigResources();3.if(configResources!=null){4.஻¯ᵨXmlBeanDefinitionReaderᩭÍᐭbeanAB*+஺5.reader.loadBeanDefinitions(configResources);6.}7.String[]configLocations=getConfigLocations();8.if(configLocations!=null){9.reader.loadBeanDefinitions(configLocations);10.}11.)Nᙠᐸ~᱄ḄAbstractBeanDefinitionReaderIᩭABÍᐭW!Javaṹ1.publicintloadBeanDefinitions(Stringlocation)throwsBeanDefinitionStoreException{2.஻:Ì?ᑮopABḄResourceLoader,ˤḄᡃᵨDefaultResourceLoader3.ResourceLoaderresourceLoader=getResourceLoader();4//᝞ÜPᨵiᑮᡃ◤⌕ḄResourceLoader,ÝGÞß5.if(resourceLoaderinstanceofResourcePatternResolver){6.//:!I!ᜐᳮᡃᙠAB¾zᵨḄᔜpattern,◤⌕ResourcePatternResolverᩭ¼ᡂ7.try{

48.Resource[]resources=((ResourcePatternResolver)resourceLoader).getResources(location);9.intloadCount=loadBeanDefinitions(resources);10.returnloadCount;11.)12.13.}14.else{15.//:ÌVWResourceLoaderᩭ¼ᡂ¾A16.Resourceresource=resourceLoader.getResource(location);17.//:ÌâãÔ[\¾AB×ᓄResourceGH$%wXmlBeanDefinitionReaderᩭᵨ18.intloadCount=loadBeanDefinitions(resource);19.returnloadCount;20.}21.)oᡃVWResourceLoaderÍᐭ3,äåᡃḄGenericApplicationContext{5ResourceLoaderGæI:Javaṹ1.publicclassGenericApplicationContextextendsAbstractApplicationContextimplementsBeanDefinitionRegistry{2.publicResourcegetResource(Stringlocation){3.஻:̯ᵨopḄloader{çODefaultResourceLoaderᩭ¼ᡂÍᐭ4.if(this.resourceLoader!=null){5.returnthis.resourceLoader.getResource(location);6.}7.returnsuper.getResource(location);8.)910.}NᡃḄFileSystemXmlApplicationContextçO[\DefaultResourceLoader-GenericApplicationContext஺VWDefaultResourceLoader^Javaṹ1.publicResourcegetResource(Stringlocation){2.஻᝞ÜOèéḄ>êë◤⌕ᵨClassPathResourceᩭ?ᑮbeanᦻDḄ3,73.if(location.startsWì(CLASSPATH_URL_PREFí){4.returnnewClassPathResource(location.substring(CLASSPATH_URL_PREFIX.Iength()),getClassLoader());5.)6.else{7.try{8.//᝞ÜOURL>êᵨUrIResourcebeanᦻDḄ3,7

59.URLurl=newURL(location);10.returnnewUrlResource(url);11.)12.catch(MalformedURLExceptionex){13.஻᝞Üð(O,ëᡃñᡲᵫᩭóAᵨôõ᪵Ḅ3,714.returngetResourceByPath(location);15.}16.}17.}ᡃḄFileSystemXmlApplicationContextÐÑçOODefaultResourceLoaderḄ55%.ḄGH!Javaṹ1.protectedResourcegetResourceByPath(Stringpath){2.if(path!=null&&path.startsWith(7H)){3.path=path.substring(l);4.)5.஻:ÌᵨᦻD]ö3,7ᩭABbeanᦻD6.returnnewFileSystemResource(path);7.}:᪵ṹç÷ᑮFileSystemXmlApplicationContextIᩭvwFileSystemResourceᩭ¼ᡂ<ᦻD]ö?ᑮξᦻDḄ3,AB஺:᪵ç$%<ᦻD]öèé7IOCξᦻDÙÚøÍ-oᯠᡃ$%ᢥ᯿:\üý<þÿᙢᙠSpringᡃᑮḄᔜ᝞ClassPathResource,URLResource,FileSystemResourceᩭᡃᵨ஺☢ᡃᑮḄResourceḄ!"#$%&'#$Ḅ•)ᑖ-ᡃ,-UAbstractBeanDefirdtionReaderzḄloadDefinitions(resource)ᩭ.ᑮ/⊤beanᦻ2Ḅ345Ḅᐭ#$78ḄᡃᵨXmlBeanDefinitionReader9Java/ṹ1.publicintloadBeanDefinitions(EncodedResourceencodedResource)throwsBeanDefinitionStoreException{2.............3.try{4.஻&=>#Resource.-UInputstreamḄIO?5.Inputstreaminputstream=encodedResource.getResource().getlnputStream();6.try{7.஻@Inputstream.ᑮXMLḄA᪆8.InputSourceinputsource=newInputSource(inputStream);9.if(encodedResource.getEncoding()!=null){10.inputsource.setEncoding(encodedResource.getEncoding());11.)12.஻&=ᐹDḄA᪆EFG#$13.returndoLoadBeanDefinitions(inputSource,encodedResource.getResource());14.)15.finally{

616.஻ᐵI@Resource.ᑮḄIO?17.inputstream.close();18.}19.}20.21.)22.23.protectedintdoLoadBeanDefinitions(lnputSourceinputSource,Resourceresource)24.throwsBeanDefinitionStoreException{25.try{26.intvalidationMode=getValidationModeForResource(resource);27.஻>#A᪆.ᑮDOM,ᯠ5KᡂbeanᙠIOCMᘤḄFG28.Documentdoc=this.documentLoader.loadDocument(29.inputSource,this.entityResolver,this.errorHandler,validationMode,this.namespaceAware);30.returnregisterBeanDefinitions(doc,resource);31.}32.............33.}ᡃᑮᐜP3ᦻ2A᪆QDOMRᯠ5STᐹDḄFG#$9Java/ṹ1.publicintregisterBeanDefinitions(Documentdoc,Resourceresource)throwsBeanDefinitionStoreException{2.//&=3A᪆VᵨXmlBeanDefinitionParserᩭA᪆xmlWḄbean3ᦻ2-XᙠḄ᱐Z[ᵨ&"A᪆ᘤ\ᵨḄXmlBeanDefinitionReader3.if(this.parserClass!=null){4.XmlBeanDefinitionParserparser=5.(XmlBeanDefinitionParser)BeanUtils.instantiateClass(this.parserClass);6.returnparser.registerBeanDefinitions(this,doc,resource);7.}8.//ᐹDḄFG#$✌ᐜ.ᑮXmlBeanDefinitionReader,xmlḄbean3ᦻ29.BeanDefinitionDocumentReaderdocumentReader=createBeanDefinitionDocumentReader()_10.intcountBefore=getBeanFactory().getBeanDefinitionCount();11.documentReader.registerBeanDefinitions(doc,createReaderContext(resource));12.returngetBeanFactory().getBeanDefinitionCount()-countBefore;13.}ᐹDḄᙠBeanDefinitionDocumentReaderKᡂR`☢•"a⌕ḄFG#$ᩭKᡂbean3ᦻ2ḄA᪆EIOCMᘤbeanḄcdᓄJava/ṹ1.publicvoidregisterBeanDefinitions(Documentdoc,XmlReaderContextreaderContext){2.this.readerContext=readerContext;

73.4.logger.debug("Loadingbeandefinitions'1);5.Elementroot=doc.getDocumentElement();6.7.BeanDefinitionParserDelegatedelegate=createHelper(readerContext,root);8.9.preProcessXmI(root);10.parseBeanDefinitions(root,delegate);11.postProcessXmI(root);12.)13.14.protectedvoidparseBeanDefinitions(Elementroot,BeanDefinitionParserDelegatedelegate){15.if(delegate.isDefaultNamespace(root.getNamespaceURI())){16.஻&=.ᑮxmlᦻ2Ḅf⁚h᝞ᔜ"bean⁚h17.NodeListnl=root.getChildNodes();18.19.஻&=Ri"⁚hSTᑖ᪆ᜐᳮ20.for(inti=0;i

846.Stringalias=ele.getAttribute(ALIAS_ATTRIBUTE);47.getReaderContext().getReader().getBeanFactory().registerAlias(name,alias);48.getReaderContext().fireAliasRegistered(name,alias,extractSource(ele));49.}50.஻&=Rᡃᨬr៉ḄbeanᐗpSTᜐᳮ51.elseif(DomUtils.nodeNameEquals(ele,BEAN_ELEMENT)){52.஻tᡲvBeanDefinitionParserDelegateᩭKᡂRbeanᐗpḄᜐᳮ&"wᒹy\ᐹDḄbeanA᪆Ḅ#$஺53.//PA᪆beanᦻ2.ᑮḄz{|ᑮBeanDefinition=}beanz{Ḅ~⌕D,IOCMᘤḄᳮR஺54.BeanDefinitionHolderbdHolder=delegate.parseBeanDefinitionElement(ele);55.if(bdHolder!=null){56.bdHolder=delegate.decorateBeanDefinitionlfRequired(ele,bdHolder);57.//&=ᔣIOCMᘤFG▭|ᑮIOCMᘤḄ!"map=58.BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistryO)_59.60.//&=ᔣIOCMᘤ〈2⊤A᪆EFGKᡂ஺61.getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolde0)_62.}63.}64.}ᡃᑮᙠparseBeanDefinitionRᐹDbeanᐗpḄA᪆WvBeanDefinitionParserDelegateᩭKᡂḄ`☢ᡃA᪆KḄbean᪵ᙠIOCMᘤFGḄ9ᙠBeanDefinitionReaderlltilslᵨḄ:Java/ṹ1.publicstaticvoidregisterBeanDefinition(2.BeanDefinitionHolderbdHolder,BeanDefinitionRegistrybeanFactory)throwsBeansException{3.4.//&=.ᑮ◤⌕FGbeanḄ_5.StringbeanName=bdHolder.getBeanName();6.஻&lᵨIOCᩭFG•ḄbeanḄ#$◤⌕.ᑮBeanDefinition7.beanFactory.registerBeanDefinition(beanName,bdHolder.getBeanDefinition());8.9.//4>#IOCMᘤEbeanὶḄSTFG10.String[]aliases=bdHolder.getAliases();11.if(aliases!=null){12.for(inti=0;i

916.}ᡃXmeanFactoryḄFGX:Java/ṹ1.//--------------------------------------------------------------2.஻&=IOCMᘤRBeanDefinitionRegistry11ḄX3.//---------------------------------------------------------------4.5.publicvoidregisterBeanDefinition(StringbeanName,BeanDefinitionbeanDefinition)6.throwsBeanDefinitionStoreException{7.8.…஻&=ḕᶍ\RBeanDefinitionḄ#$9.஻ᐜᙠMᘤ=[ᨵ\Ḅbean,᝞¡ᨵ¢£¤¥஺10.ObjectoldBeanDefinition=this.beanDefinitionMap.get(beanName);11.if(oldBeanDefinition!=null){12.if(Ithis.allowBeanDefinitionOverriding){13....................14.)15.else{16.஻PbeanḄᑮIOCMᘤ¦17.this.beanDefinitionNames.add(beanName);18.}19.஻&=PbeanḄEBean3ὶᩭ|ᑮ•"HashMap¦,IOCMᘤ>#&"Mapᩭ§¨Mᘤ=ḄBean3z{஺20.this.beanDefinitionMap.put(beanName,beanDefinition);21.removeSingleton(beanName);22.}&᪵©Kᡂ\Bean3ᙠIOCMᘤḄFG©ª«IOCMᘤSTᳮEᵨ\஺@☢Ḅ/ṹᩭᡃ¬•`IOCMᘤcdᓄḄ®Z¯°9*cdᓄḄᐭ²ᙠMᘤXḄrefresh஺lᵨᩭKᡂ*Rbean3ᢗᐭ஺CMᘤᵨḄ´loadBeanDefhtion,ᐸḄᜧ·#$᝞`9>#ResourceLoaderᩭKᡂᦻ2¸ḄDefaultResourceLoader78ḄX¹`ᦻZº©v£\ResourceLoaderḄXª4@w»¼ᦻ2½URLWᩭQ¸஺᝞¡XmeanFactory¾QIOCMᘤ¿À◤⌕Qᢣbean3Ḅ©Âbean3ᦻ2¹>#ᡂResourceᩭ«IOCMᘤᜐᳮḄMᘤ>#BeanDefinitionReaderᩭKᡂ3z{ḄA᪆EBeanz{ḄFGÃ~ÄᵨḄXmlBeanDefinitionReaderᩭA᪆beanḄxml3ᦻ2-▭Ḅᜐᳮ#$tᡲvBeanDefinitionParserDelegateᩭKᡂḄ@%.ᑮbeanḄ3z{&Åz{ᙠSpringᵨBeanDefinitionRᩭ⊤!&"ª4ÆᡃÇᑮloadBeanDefinition,RegisterBeanDefinition&ÅÈᐵḄ´-}ÉQᜐᳮBeanDefiNtinÊËḄloCMᘤA᪆.ᑮBeanDefinition45◤⌕Pᙠ10cMᘤFG&ᵫIOCXBeanDefinÍonRegistry²ᩭX஺FG#$©ᙠIOCMᘤᑁ)§¨Ḅ•"HashMapᩭÏÐ.ᑮḄBeanDefinitionḄ#$஺&"HashMaploCMᘤᢝᨵbeanz{ḄÒᡠ45RbeanḄÔ¾ÉÕÖ&"HashMapᩭXḄ஺*ᯠ5ᡃ©ª4>#BeanFactoryEApplicationcontextᩭ×ØᑮSpringIOCḄÊË\.ᙠᵨIOCMᘤḄ¹᎛ᡃFÛᑮ◀\ÝÞßᔠ/ṹáᜧâᦪ4äåloCæçèᑏḄêᵨ$ë/ṹK

10ᐰ[ᵨᐵí᝞îᑮïðᔆòQMᘤóP&ÅRôMᘤᳮḄᐸ}Rõᙠ!஺®ZḄöᶍPðᔆ|ᑮ÷Ḅᙢᨬø|ᙠR⚜úᵨḄ`ᦻᨵÛ3Ḅᙢ4û/ṹó▭◤⌕üýðᔆḄᙢ஺SpringZº\RþÿᐭwebᵨᵨḄᵨᦻᐸᙠServletContextḄ᪾஺ᐹḄᦻ஺ᙠ!ᵨSpringIOC"ᘤḄ$᎛ᡃ'(◤⌕+,-.ᭆ01Beanfactory2Factorybean,ᐸBeanFactoryᢣḄ5IOC"ᘤḄ6789᝞Applicationcontext,XmlBeanFactory;<=>5IOC"ᘤḄᐹ⊤◤⌕!ᵨ@A᪵Ḅ"ᘤᵫDᡝFGHSpringIᡃ'JKLMNḄ⌱P஺QFactoryBeanR5S.ᙠIOC"ᘤTUᳮḄS.bean,5WᔜYᜐᳮ[2\]!ᵨḄ78,Factorybeanᙠ◤⌕$_`aS.W8QbcdFactoryBeanᩈḕᡃ'ghiᡂ5S.78kᔆWhḄmᵨcdḄ5kᔆ`_Ḅ_n஺ᡠᨵḄFactorybean>ᱯrḄorg.springframework.beans.factory.FactoryBeanftn,s!ᵨ"ᘤfactorybeanḄ$᎛t"ᘤbuc|H|factorybeanvwQ5cIxᐸ`ᡂḄW8஺SpringᒹzLᜧ|ᑖḄ~ᵨ\]278ḄFactorybeanḄᐸᒹz1WJNDIḄᜐᳮWᳮW8ḄᜐᳮWឋᳮḄᜐᳮWRMIᳮḄᜐᳮ;<=ᡃ'>iᡂ5ᐹḄkᔆiᡂ5SPRINGIᡃ'Ḅkᔆ஺5Spring~[!ᵨ78kᔆIᡃ'ᜓLSᑡkᔆᩭ`_S=ᱯGḄW8◀ᡃ'kḄkᡃ'⌕!ᵨ$R◤⌕ᙠIOC"ᘤḄ!ᵨL஺ᙠᡃ'ᩭiiᙠSpringḄ¡¢ᑴSpringᨵ3.᪗¡ContextRefreshEvent,ContextCloseEvent,RequestHandledEvent¥'~[ApplicationEvent¦§x᪵Ḅ᝞¨◤⌕©Gª$«R◤⌕ApplicationEvent¦§᯿ContextCloseEventḄGᑴ©Ḅ¡1Javaṹ¯1.publicclassContextClosedEventextendsApplicationEvent{2.3.publicContextClosedEvent(ApplicationContextsource){4.super(source);5.)6.7.publicApplicationcontextgetApplicationContext(){8.return(Applicationcontext)getSource();9.)10.}~[°ApplicationEventPublishAware¦§¡±²ᘤ὚ᔠᑮApplicationcontext<᪵!ᵨApplicationcontext᪾ᩭ¶⌴2¸¹¸º»ᙠApplicationcontextbeanLᙠ¸¹¸ºḄ[¦¼ὅ~[ApplicationListener¦ᦈ¸º஺9᝞¿¦!ᵨSpringḄScheduleTimerTask2TimerFactoryBeanIG$ᘤG$_`¸ºᐹÀSpring᪾ÁÂ6Ã,TimerFactoryBean5——.kᔆbean,WᐸU¯ḄScheduleTimerTaskÅÆLᜐᳮÇÈὃScheduleTimerTaskḄ±hᨬmᵨḄ5jreḄTimerTask1Javaṹ1.publicvoidsetRunnable(RunnabletimerTask){2.this.timerTask=newDelegatingTimerTask(timerTask);3.)

11ᙠËÌÈLS.G$±〈¸ºḄÎÏsᯠ~[G$ᘤᐸ¥ḄÑᨵ-Y11.GªMethodlnvokingTimerTaskFactoryBeanGª⌕᡻ÔḄᱯGbeanḄᱯGW◤⌕Õ@AÅÔÖ×GªØ2.GªTimerTaskÙ~[extendsTimerTaskᩭÚᑮx$W◤⌕Õ@AÅÔ©Gªᯠ◤⌕GªᐹḄG$ᘤᦪ~[ScheduledTimerTaskḄᦪ2timerTaskᩭÜᡂ5h◤⌕GªḄᐹÝឋtimerTask5ᙠÞ☢àáGªḄbeanJavaṹ1.privateTimerTasktimerTask;2.3.privatelongdelay=0;4.5.privatelongperiod=0;6.7.privatebooleanfixedRate=false;ᨬ◤⌕ᙠApplicationcontextâã◤⌕gScheduledTimerTaskᑮFactoryBean-TimerFactoryBean,<᪵ᵫIOC"ᘤᩭUᳮG$ᘤL஺᯿TimerFactoryBeanḄÝឋGᑴSäG$ᘤ஺Javaṹ1.publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{2.3.protectedfinalLoglogger=LogFactory.getLog(getClass());4.5.privateScheduledTimerTask[]scheduledTimerTasks;6.7.privatebooleandaemon=false;8.9.privateTimertimer;10.1112.)᝞¨⌕±〈$«ᡃ'R◤⌕ᙠGªḄScheduledTimerTasks4'publishGªḄ¡L஺ᐹὃËÎÏḄ⌫bᣵIOCḄ÷ø1)☢ᡃ'ᑖ᪆LIOC"ᘤvwḄ☢ᡃ'iiᙠᐺûḄwebü᛻SpringIOC"ᘤ5þ᪵TᢗᐭᵨḄ஺ᓫḄᙠwebᘤServletContextSpringḄIOCᘤ:᛻Ḅ•IOCᘤḄ஺ᐸ✌ᐜ◤⌕Ḅ&᪷()ᦻ+()ᦻᢝᨵḄ./0ᨵ12.ᦪ456.789ᱥ;ᳮᘤ=ᔜ?@A.஺ᙠ+()ᦻḄBẠ(webMVCDᐵFGᨵH()ᦻᩭJ5KᑴᘤMNḄMVC.+᪵P᪀ᡂSHATᓄḄ()ᦻV᪀஺ᙠwebᘤWXSpring

12ᵨZ[P&H+()ᦻḄZ஺SpringwebᵨS()ᦻḄ᡽]^_WebApplicationContext:Java`ṹ1.publicinterfaceWebApplicationContextextendsApplicationcontext{2.஻+cdeḄfgᵨhᙠServletContext56᪷()ᦻ3.StringROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName()+".ROOT";4.……5.஻WebApplicationContextᩭ◤⌕iᑮWebᘤḄServletContext6.ServletContextgetServletContext();7.}kHlḄWXZSpringGmᵨHnoḄpqXmlWebApplicationContext-+()ᦻpqᙠwebᘤḄ᪷()ᦻᘤrᩭᐹḄZᙠ)☢ᡃvGwxᑖ᪆஺Java`ṹ1.publicclassXmlWebApplicationContextextendsAbstractRefreshableWebApplicationContext{2.3./**+&web}~DᐵḄᵨᩭDoḄ᪷()ᦻbeandeḄ5*/4.publicstaticfinalStringDEFAULT_CONFIG_LOCATION="/WEB-INF/applicationContext.xml”;5.publicstaticfinalStringDEFAULT_CONFIG_LOCATION_PREFIX=VWEB-INF/"6.publicstaticfinalStringDEFAULT_CONFIG_LOCATION_SUFFIX=7.8.஻ᡃvᑮS៉ḄloadBeanDefinition,Pᡃv☢IOCᘤḄᑖ᪆H᪵,+ZᙠᘤḄrefresh஺Ḅ᎛ᡣX஺9.protectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwslOException{10.஻hXmlWebApplicationContext,ᯠmᵨḄ&XmeanDefinitionReaderᩭbeandeᩭ᪆11.XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);12.13.beanDefinitionReader.setResourceLoader(this);14.beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));15.16.initBeanDefinitionReader(beanDefinitionReader);17.loadBeanDefinitions(beanDefinitionReader);18.}19.20.protectedvoidinitBeanDefinitionReader(XmlBeanDefinitionReaderbeanDefinitionReader){21.

1322.஻mᵨXmlBeanDefinitionReaderᩭᐭbeande23.protectedvoidloadBeanDefinitions(XmlBeanDefinitionReaderreader)throwsBeansException,lOException{24.String[]configLocations=getConfigLocations();25.if(configLocations!=null){26.for(inti=0;i

141.஻+c᪷.ᓃ)ᦻº»ᓄ஺2.publicvoidcontextlnitialized(ServletContextEventevent){3.஻+câ◤⌕ḄContextLoader4.this.contextLoader=createContextLoader();5.஻+cmᵨContextLoader᪷()ᦻᐭº»ᓄ6.this.contextLoader.initWebApplicationContext(event.getServletContext());7.}ContextLoader᪷(ã.ᦻḄZᡃv/0ᙠContextLoaderᑮØJava`ṹ1.publicWebApplicationContextinitWebApplicationContext(ServletContextservletContext)2.throwsHlegalStateException,BeansException{3.஻+cᐜ&«&äåᙠServletContext5ᙠ()ᦻ᝞çᨵ☢äårᐭᡈὅ&ÊᦻÈᨵ┯é஺4.if(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)!=null){5.஻ê^ëìíf6..............7.)8.9......................10.try{11.//+cᐭ᪷()ᦻḄ᱄()ᦻ12.Applicationcontextparent=loadParentContext(servletContext);13.14.஻+câ᪷()ᦻ᦮ᵨḄ()ᦻ¬ï®5ᑮServletContextð,ñò+cmᵨḄServletContextḄÌឋÍ&15.//ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,0ÉḄᵨ·&᪷4+ÌឋÍᩭ6i᪷()ᦻḄ-óóôõ()ᦻḄ᱄()ᦻ16.this.context=createWebApplicationContext(servletContext,parent);17.servletContext.setAttribute(18.WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this,context);19...................20.21.returnthis.context;22.}23.....................24.}᪷()ᦻḄ᱄()ᦻmᵨḄ&)☢Ḅ`ṹ6öhᙠweb.xmldeḄÛᦪØlocatorFactorySelector,+&/⌱ÛᦪØJava`ṹJ1.protectedApplicationcontextloadParentContext(ServletContextservletContext)

152.throwsBeansException{3.4.Applicationcontextparentcontext=null;5.6.StringlocatorFactorySelector=servletContext.getlnitParameter(LOCATOR_FACTORY_SELECTOR_PARAM);7.StringparentContextKey=servletContext.getlnitParameter(LOCATOR_FACTORY_KEY_PARAM);8.9.if(locatorFactorySelector!=null){10.BeanFactoryLocatorlocator=ContextSingletonBeanFactoryLocator.getlnstance(locatorFactorySelector);11.12.஻iᑮ᪷()ᦻḄ᱄()ᦻḄøᵨ13.this.parentContextRef=locator.useBeanFactory(parentContextKey);14.஻+ciᑮ᪷(ã.ᦻḄ᱄()ᦻ15.parentcontext=(Applicationcontext)this.parentContextRef.getFactory();16.}17.18.returnparentcontext;19.}iᑮ᪷()ᦻḄ᱄()ᦻ0ÉP&᪷()ᦻḄâZØJava`ṹD1.protectedWebApplicationContextcreateWebApplicationContext(2.ServletContextservletContext,Applicationcontextparent)throwsBeansException{3.஻+c◤⌕ùdᡃvᐭḄ᪷WebApplicationḄNúᵫᙠweb.xmlÊḄcontextclassÊḄÛᦪ/0ödᡃv◤⌕ᐭ¨©᪵ḄApplicationcontext,4.஻᝞çüᨵmᵨnoḄ஺5.Classcontextclass=determineContextClass(servletContext);6..............7.஻+cP&()ᦻḄâZ8.ConfigurableWebApplicationContextwac=9.(ConfigurableWebApplicationContext)Beanlltils.instantiateClass(contextClass);10.஻+cJᢝ᱄()ᦻServletContextḄøᵨᑮ᪷()ᦻ11.wac.setParent(parent);12.wac.setServletContext(servletContext);13.14.஻+cÇweb.xml6iDᐵḄº»ᓄÛᦪ15.StringconfigLocation=servletContext.getlnitParameter(CONFIG_LOCATION_PARAM);16.if(configLocation!=null){17.wac.setConfigLocations(Stringlltils.tokenizeToStringArray(configLocation,18.ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));19.}

1620.஻+cWebApplicationContextº»ᓄᡃvᑮS៉Ḅrefreshýᵨ஺21.wac.refresh();22.returnwac;23.}º»ᓄ᪷ApplicationcontextÉþᐸ5ÿᑮSevletContext᪵ᐰḄᐵ᦮ᵨḄᦻ஺᪷ᦻḄDispatcherServletᓄ!Ḅ"᎛$%!ApplicationcontextḄ᱄ᦻ஺ᙠ(DispatcherServlet)ᑖ᪆Ḅ"᎛ᡃ-.//ᑮ஺3.1ᡂ(ContextLoaderListenerḄᓄTomcat3ᓄDispatchServlet,-456ᡃ-ᙠweb.xml78ᐭ:;<=>?஺DispatcherServlet!ḄApplicationcontext,@"!ḄᦻḄ"᎛AServletContext6ᑮ᪷Bᦻ$%᱄B.ᦻᯠD(!ḄB.ᦻ<=ᓄEᨬGᑮServletContextHIJKLᵨ஺.ADispatchServletḄ᱄MFrameworkServletḄNṹ/ᑮᜧQḄᓄRS᦮ApplicationcontextḄTRSKContextLoderTḄRSUMV:JavaNṹ1.protectedfinalvoidinitServletBean()throwsServletException,BeansException{2.............3.try{4.஻Z[(ᦻḄᓄRS஺5.this.webApplicationContext=initWebApplicationContext();6.஻ᙠ1ᡂ(ᦻḄᓄRS\]᪷^bean_`abMVC᪾dḄᔜf⌕ᐗi7.initFrameworkServlet();&)9.10.)(initWebApplicationContext஺jᵨḄNṹ᝞lJavaNṹU1.protectedWebApplicationContextinitWebApplicationContext()throwsBeansException{2.஻ZjᵨWebApplicationContextUtils☟᝱Mᩭ6ᑮ᪷ᦻ3.WebApplicationContextparent=WebApplicationContextUtils.getWebApplicationContext(getServletContext());4.5.஻TpqDispatcherServletḄI.B.ᦻᐸᦻsMLᵨtuḄᙠFrameworkServlet>?vḄlDEFAULT_CONTEXT_CLASS=XmlWebApplicationContext.class;6.WebApplicationContextwac=createWebApplicationContext(parent);7............8.if(isPublishContext()){9.஻wpqḄᦻGᑮServletContext,yzLᵨḄ{ឋ}[KpqServlet}UᐵḄ஺10.StringattrName=getServletContextAttributeName();11.getServletContext().setAttribute(attrName,wac);12.)13.returnwac;

1714.)ᐸᡃ-/ᑮjᵨWebApplicationContextUtilsḄ☟᝱~6ᑮ᪷Applicationcontext:JavaNṹ1.publicstaticWebApplicationContextgetWebApplicationContext(ServletContextsc){2.஻ᓫAServletContextR{ឋ}6ᑮ᪷ᦻ3.Objectattr=sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);4...........5.return(WebApplicationContext)attr;6.)7.ᯠTDispatcherServlet!ḄWebApplicationContext:8.protectedWebApplicationContextcreateWebApplicationContext(WebApplicationContextparent)9.throwsBeansException{10...........11.஻ZLᵨBeanlltils6ᑮWebApplicationContext,Contextclass[q☢>?vḄDEFAULT_CONTEXT_CLASS=12.//XmlWebApplicationContext.class;13.ConfigurableWebApplicationContextwac=14.(ConfigurableWebApplicationContext)Beanlltils.instantiateClass(getContextClass());15.16.஻Z_`᱄ᦻ[ᙠContextLoader•I'iHḄ᪷ᦻ17.wac.setParent(parent);18.19.஻ᶇServletContextḄᵨKUᐵḄ_`ab஺20.wac.setServletContext(getServletContext());21.wac.setServletConfig(getServletConfig());22.wac.setNamespace(getNamespace());23.24.஻Z6ᑮApplicationcontext_`ᦻḄ`25.if(getContextConfigLocation()!=null){26.wac.setConfigLocations(27.Stringlltils.tokenizeToStringArray(28.getContextConfigLocation(),ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));29.}30.31.஻ZjᵨApplicationcontextḄᓄRS@᪵◤⌕Lᵨrefresh()32.wac.refresh();33.returnwac;34.}

184.ᯠ[DispatchServlet(SpringMVCḄ_`RS✌ᐜ(_`ᦻḄ>?ᐗi<=_`-yz"᎛ᡃ-ḄWebApplicationContextᩭzᕡḼDispatcherServletᨵ!Ḅ>?.◤⌕Aweb.xmlbeanḄ_`abᡃ-LᵨᓫḄxmlᦻᩭ_`MVCᔜ⌕i>?ZKwebᘤUᐵḄ8RS¡▭1ᡂB.☢ḄᜐᳮK¥ḄSpringᵨS;Ḅ¦ᑏ¨ᨵ©ª«ᜧḄ¬ᡃ-ᐜ//MVCḄᓄRSlJavaNṹ1.protectedvoidinitFrameworkServlet()throwsServletException,BeansException{2.initMultipartResolver();3.initLocaleResolver();4.initThemeResolver();5.initHandlerMappings();6.initHandlerAdapters();7.initHandlerExceptionResolvers();8.initRequestToViewNameTranslator();9.initViewResolvers();10.}5.᪵MVCḄ᪾dᩭDispatchServlet(®ᑮḄHTTPRequest<=ᑖ¯ᜐᳮᵫdoService஺1ᡂᐹ²ḄMVCᜐᳮRSᡃ-ᙠdoDispatch()1ᡂᐸᒹ´LᵨCommandµ¶᡻=¸¹ºµ»ᦪ^½¾ᜐᳮᡃ-¿.ᙠDispatcherServletḄNṹ/ᑮlJavaNṹ1.protectedvoiddoService(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2.……3.try{4.doDispatch(request,response);5.}6..........7.)¡▭ḄÀᑖ¯ᵫdoDispatch(requestjesponse)ᩭ1ᡂlJavaNṹ1.protectedvoiddoDispatch(finalHttpServletRequestrequest,HttpServletResponseresponse)throwsException{2............3.//[Spring>?Ḅ᡻=¸Z.ᔣÃÄ᧜ÆᐵÇ(•ḄhandlerK>?ḄUᐵÉ:Êᘤ”4.HandlerExecutionChainmappedHandler=null;5.6.……7.try(8.஻ᡃ-Ì៉ḄModelAndViewᙠZÎÏ஺9.ModelAndViewmv=null;10.try{

1911.processedRequest=checkMultipart(request);12.13.஻ZÐᐹrequestḄÑᦪK᧜ÆᐵÇ>?Ò>LᵨḄhandler14.mappedHandler=getHandler(processedRequest,false);15.16.……17.஻Z[handlerḄjᵨRSMVCommandµ¶Ḅexecute.18.HandlerAdapterha=getHandlerAdapter(mappedHandler.getHandler());19.mv=ha.handle(processedRequest,response,mappedHandler.getHandler());20.21.........22.//ZÓµ»ᦪ^RÔÕ<=ÖÏ23.if(mv!=null&&!mv.wasCleared()){24.render(mv,processedRequest,response);25.}26.27.)᪵ᐹ²ḄMVCµ»Ḅ¡Ïᵫbean_`ᦻZ>?vḄviewresolver,handler¾Mᩭ¡ÏᵨᡝNṹḄØÙ஺Ú\☢ḄRSᡃ-/ᑮᙠwebᘤServÛContext.ᢝᨵÇᑡḄwebᦻÞᙠ᦮webᦻGᙠ᪷ᦻᩭ$%ᐸßServletᦻḄ᱄ᦻ஺᪷ᦻ[ᵫContextLoader8ᐭE<=ᓄḄ(ᡃ-ḄwebᵨDispatcherSerlvet8ᐭEᓄ!ḄᦻᦻḄ᱄ᦻ[᪷ᦻEàᡃ-ÙAServletContext᪷^ServletḄ}áᩭIJᑮᡃ-◤⌕Ḅ(ServletḄᦻâ[᪷ᦻḄ}á[ᵫSpringãä>Ḅ஺DispactcherServletḄᦻ[ᡃ-3¯SpringMVCᵨḄIOCᘤ஺ᐹ²ḄwebÀᜐᳮᙠᦻ²Ç1ᡂᵫDispactcherServletᩭ1ᡂ☢(MVCḄå$)•ᜧQḄæç☢ᡃ-ᐹ²SpringMVCḄ᪾d¡Ï$•èéḄᑖ᪆஺☢ᡃ-//SpringJDBCUᐵḄ¡ÏᙠSpringJdbcTemplate[LᵨḄMᩭêëᵨᡝS;ì$ᦪ^íᙠJdbcTemplate%ᵨᡝS;îHïðñᑭḄᦪ^íì$~ó᝞ôõÐö½ÞàᙠSpringᨵïðMVJdbcTemplateḄµ÷ó᝞HibernateTemplate½½-/ᩭ[Rod.JohnsonḄøᵨù•úÞûsTemplate¿[RÛjüᦪCaHBackMḄLᵨᩭ1ᡂØÙḄýᡝ◤⌕ᙠÛjþ¡Ï!◤⌕Ḅ>ᑴ᝞ᵨᡝ⌕ᵨḄSQL஺SpringᦪḄᡃ!"#$ᡂḄ&'!ᡝᵨ஺()ᩭ+ᦪḄᵨ',ᵨ-./Ḅ&0ᩭ᝞1Java2ṹ1.JdbcTemplate=newJdbcTemplate(datasource);2.JdbcTemplate.execute(newCallBack(){3.publicCallbacklnterfacedolnAction(){4.……5.஻ᵨᡝ67Ḅ2ṹᡈὅ+Spring:ᡃḄ2ṹ6.)7.)

20ᙠ<=>?ᐭḄA◤⌕ᡝᓄḄ2ṹᵫSpringᩭEᡈὅ◤⌕ᡝFGHIJKLᡂ஺M☢OᡃᐹQRRᙠJdbcTemplate>Ḅ2ṹAS᪵LᡂUḄᡃVJdbcTemplate.execute()WX&'AᙠJdbcTemplate>Yᐸ[&'ᵨḄ\]&'^(ᡝFGᵨX&'ᩭ᡻\]ḄSQL1Java2ṹ1.publicObjectexecute(ConnectionCallbackaction)throwsDataAccessException{2.஻`aᑮᦪcdὶf3.Connectioncon=DataSourceLJtils.getConnection(getDataSource());4.try{5.ConnectionconToUse=con;6.஻ᨵhᱯjḄᦪcd◤⌕ᡃᵨᱯkḄ&'ladatasource7.if(this.nativeJdbcExtractor!=null){8.//ExtractnativeJDBCConnection,castabletoOracleConnectionorthelike.9.conToUse=this.nativeJdbcExtractor.getNativeConnection(con);10.}11.else{12.//Createclose-suppressingConnectionproxy,alsopreparingreturnedStatements.13.conToUse=createConnectionProxy(con);14.)15.஻`ᵨḄAm⌴oᩭḄ-./Ḅ&',qrAᵨᡝFG◤⌕CallBackfsḄᙢ&஺16.returnaction.dolnConnection(conToUse);17.)18.catch(SQLExceptionex){19.஻᝞uᣓᣍᑮᦪcxyz{ᦪc|ὶf}~(XSpringᣚḄSpringᦪcdyz20.஻ᡃ⍝Spring"(X7ḄI1EA{hᦪc|z(ᑮIḄyzQ"஺21.DataSourcelltils.releaseConnection(con,getDataSource());22.con=null;23.throwgetExceptionTranslator().translate("ConnectionCallbackH,getSql(action),ex);24.)25.finally{26.஻ᨬS᪵{ᦪcdf}~27.DataSourcelltils.releaseConnection(con,getDataSource());28.}29.}JdbcTemplate>Ḅᐸ[&'᝞query,update,executeḄᡃRRquery()1Java2ṹ1.publicObjectquery(PreparedStatementCreatorpsc,finalPreparedStatementSetterpss,finalResultSetExtractorrse)2.throwsDataAccessException{3................

214.஻`ᵨ"ᡃ☢RᑮḄexecute஺\]&'ᯠ`ḄASpringᡃLᡂḄ᩵F5.returnexecute(psc,newPreparedStatementCallback(){6.publicObjectdolnPreparedStatement(PreparedStatementps)throwsSQLException{7.஻ᜓu¡8.ResultSetrs=null;9.try{10.஻`¢£SQL¤ᦪ11.if(pss!=null){12.pss.setValues(ps);13.}14.஻`᡻ḄSQL15.rs=ps.executeQuery();16.ResultSetrsToUse=rs;17.if(nativeJdbcExtractor!=null){18.rsToUse=nativeJdbcExtractor.getNativeResultSet(rs);19.}20.஻¥◤⌕Ḅ¦§¡ᔠ21.returnrse.extractData(rsTollse);22.}23.finally{24.஻ᨬᐵªᙠḄ«¬¡ᦪcdfḄ}~ᙠexecute஺>~r®ᡃᙠ☢ᑖ᪆ḄRᑮ±᪵஺25.Jdbclltils.closeResultSet(rs);26.if(pssinstanceofParameterDisposer){27.((ParameterDisposer)pss).cleanupParameters();28.}29.}30.}31.})´32.}µ¶/DataSourceUtilsᩭᵨᩭᦪcdfoᳮḄ¸⌕¹ᐹ᝞ᡭ»¼ᐵªᦪcdf\]½E1Java2ṹ1.publicstaticConnectiondoGetConnection(DataSourcedataSource)throwsSQLException{2.஻{ᦪcdf~ᑮ¾¿ᳮ`☢oᳮ3.ConnectionHolderconHolder=(ConnectionHolder)TransactionSynchronizationManager.getResource(dataSource);4.if(conHolder!=null&&(conHolder.hasConnection()||conHolder.isSynchronizedWithTransaction())){5.conHolder.requested();6.if(!conHolder.hasConnection()){

227.logger.debug("FetchingresumedJDBCConnectionfromDataSource");8.conHolder.setConnection(dataSource.getConnection());9.)10.returnconHolder.getConnection();11.)12.//`aᑮ◤⌕Ḅᦪcdfᙠ¢ÁᦻÃ>67ÄḄ஺13.logger.debug("FetchingJDBCConnectionfromDataSource");14.Connectioncon=dataSource.getConnection();15.16.if(TransactionSynchronizationManager.isSynchronizationActiveO){17.logger.debug("RegisteringtransactionsynchronizationforJDBCConnection'1);18.//UsesameConnectionforfurtherJDBCactionswithinthetransaction.19.//Thread-boundobjectwillgetremovedbysynchronizationattransactioncompletion.20.ConnectionHolderholderToUse=conHolder;21.if(holderToUse==null){22.holderToUse=newConnectionHolder(con);23.}24.else{25.holderTollse.setConnection(con);26.}27.holderToUse.requested();28.TransactionSynchronizationManager.registerSynchronization(29.newConnectionSynchronization(holderTollse,dataSource));30.holderToUse.setSynchronizedWithTransaction(true);31.if(holderToUse!=conHolder){32.TransactionSynchronizationManager.bindResource(dataSource,holderToUse);33.}34.}35.36.returncon;37.}±ᡃ▭ḄDataSourceÆAS᪵aᑮḄÇÈÉÊᡃ◤⌕ᙠMᦻ>o¢£1ËEJdbcTemplate᱄/JdbcAccessorḄÍឋÏᙠ1Java2ṹ1.publicabstractclassJdbcAccessorimplementsInitializingBean{2.3./**`AᡃÑÒÓᐭᦪcdᦪcÔḄÕ^*/4.privateDataSourcedataSource;5.6./**HelpertotranslateSQLexceptionstoDataAccessExceptions*/7.privateSQLExceptionTranslatorexceptionTranslator;8.9.privatebooleanlazylnit=true;

2310.11....................12.)DataSourceḄ×ØÙᡃ67ApacheJakartaCommonsDBCPᡈὅC3P0!ḄDataSourceᩭLᡂᯠÚ⌕ᙠMᦻ>¢£ÄrÛÜᵨ"஺Ý☢ᡃRÞUJdbcTemplate!"#$ßᓫ¼áâãäåA᝞u◤⌕áæçèḄéÆÜêá☢ᔣÆḄ&'ᩭìíᦪcd஺Springᡃ!"org.springframework.jdbc.object`☢ᒹï"SqlQuery.SqlMappingQuery,SqIUpdate¼StoredProcedure/h/ASpringJDBCðᵨFGÛÜᵨḄ¸⌕/åᡃ⌕Óᵨh/Ḅ᎛ᵨᡝ◤⌕[¢£Ä(XJdbcTemplateEᐸ\ᩈḄ½EḄ஺᝞+ᡃᵨMappingSqlQueryᩭó⊤ᦪcõf᧜÷ᑮ(XÆ¡ᔠ-ᐹQÛܤὃú>ḄWû1.ᡃ◤⌕ýþDataSource¼sqlÿᢝᨵḄMappingSqlQuery2.ᯠᡃ◤⌕⌴ḄSqIParameter,ᐹḄᡃᙠMappingSqlQueryḄ᱄RdbmsOperationᑮ!Java"ṹ1.publicvoiddeclareParameter(SqlParameterparam)throwsInvalidDataAccessApiUsageException{2.஻᝞&'()*+,-./ᑣ1'(2ᦔ3.if(isCompiled()){4.thrownewlnvalidDataAccessApiUsageException("Cannotaddparametersoncequeryiscompiled")45.}6.஻56ᦪ89:'(7.this.declaredParameters.add(param);;Ḅ?•<ᑡ⊤!Java"ṹ1./**ListofSqIParameterobjects*/2.privateListdeclaredParameters=newLinkedList();<ᑡ⊤ᙠcompileḄ.CD+Eᵨ஺3.ᯠᵨᡝCI◤⌕MappingSqlQueryḄmapRowJK/LᐹḄResultSetᦪMNᡂᡃ◤⌕Ḅ/?ᡃP"EᵨḄQR஺1,2,3S▭UVᡃWXY

246.//ᡃtuᑮXJdbcTemplate,5EᵨJdbcTemplateᩭvᡂᦪM᧤Ḅ^;_^/ᡠᡃyJdbcTemplate?Z[Ḅ_^஺7.returngetJdbcTemplate().query(newPreparedStatementCreator(sqlToUse,parameters),rowMapper);8.}ᙠ5ᡃuᑮtemplate`zḄ{|bᵨ}JdbcTemplateḄᮣEᵨ஺.Eᵨ/ᡃXP"ResultSetLᐸḄᦪMᓄVᑡ⊤Ḅ.C஺ᙠ5ᡃ◤⌕SQLkl}SqIParameter-᝞&◤⌕Ḅ/SQLklᡃḄ⌕X஺?ᮣEᵨJdbcTemplateḄY

251.publicvoidsetBlobAsBinaryStream(2.PreparedStatementps,intparamIndex,Inputstreambinarystream,intcontentLength)3.throwsSQLException{4.//.JDBCᩭvᡂBLOBᦪMḄ_^/Oracle,SpringXOracleLobHandlerᩭÂᢝBLOB_^஺5.ps.setBinaryStream(paramlndex,binarystream,contentLength);6.............7.)U☢ᑮḄ?ÄÄÅÅḄSpringJDBCEᵨḄ/uᑮEᵨSpringJDBCÆÇᡃvᡂᦪMḄ_^஺SpringᦪM_^ᨬZ[Ḅ¡?.JdbcTeamplate}ᵨḄIÉd´ᦪᩭḄ/ᙠÊËᓃÍXRMDBḄ_^ᩭÆÇᡃ¥ÎᑭḄᦪMḄᦪM9:_^-¸¹5ÐᨵÑᐭᔣHibernate᪵Ḅ0/RQᫀ஺0/RQᫀḄÂᢝ/Springᵫᐸᒹᩭvᡂ¡஺¬ᑮᐵiexecute}updateQRËÖḄ×Ø/updateQRÙ³Ḅ?ÚÛÜḄmnᦪÝḄY<Þᦪ/ß᝞&ᐭ6ᦪḄ/EᵨḄ?java.sql.PreparedStatement,;executeQRà?Eᵨjava.sql.Statement,áJÚ6ᦪ/;ßáÙ³ÚÛÜmnḄÞᦪ/¥〉ᔠiä}åæ⊤Ḅkl/;updateQR¥〉ᔠi£ᐭ/¥¦}ᑤ◀_^/é?ᡃᙠEᵨê◤⌕¸¹Ḅ஺ë☢ᡃSpringMVC᪾í"ṹ9:ᑖ᪆/iwebApplicationContextḄðᐵᑖ᪆6ñòḄᦻ᫏/ᡃ5Ḽᑖ᪆SpringWebMVC᪾íḄ.ᡃöᑖ᪆DispatcherServletᐭ!Java"ṹ1.஻5?DispatcherServletḄ÷øᓄQR/᪷MúûᡃQ☢Ḅuᑮᔜ

266.getWebApplicationContext(),HandlerMapping.class,true,false);7.if(!matchingBeans.isEmpty()){8.this.handlerMappings=newArrayList(matchingBeans.values());9.//@^order*ឋᩭ0handlerMappingᩭᙠlist$᣸L10.Collections.sort(this.handlerMappings,newOrderComparator());11.)12.)13.else{14.try{15.Objecthm=getWebApplicationContext().getBean(HANDLER_MAPPING_BEAN_NAME,HandlerMapping.class);16.this.handlerMappings=Collections.singletonList(hm);17-)18.catch(NoSuchBeanDefinitionExceptionex){19.//Ignore,we'lladdadefaultHandlerMappinglater.20.}21.)22.23.஻᝞`ᙠEaᦻ$bᨵGHḄcdeᡃ#fᵨhiḄBeanNamellrlHandlerMapping24.if(this.handlerMappings==null){25.this.handlerMappings=getDefaultStrategies(HandlerMapping.class);26.......................27.)28.}j᪵lmEᦻn᛻OPpqᡃ#r☢Ḅ0IOCᘤᙠwebn᛻$tVḄᑖ᪆஺DispatcherServlet)GH!ḄᡠᨵHandlerMappingUtV!wᙠMNList@xPyfᵨNXḄzMNᐗ|UMNhandlerMappingḄ%&}•~z•NhandlerMappingOPᢝᨵᑡURLᑮSpringControllerḄ᧜,᝞SimpleUrlHandlerMaaping$GH!Nmapᩭᢝᨵ•ᑡḄ᧜ᐵ஺DisptcherServlet^HandlerMappingfmWebᵨLGMN᡻ᡃ#ᙠHanderMapping$:ᑮḄd᪵HandlerMapping•N;Java<ṹ1.publicinterfaceHandlerMapping{2.publicstaticfinalStringPATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE=3.Conventions.getQualifiedAttributeName(HandlerMapping.class,"pathWithinHandlerMapping");4.஻᝕:▭EYZM•NHandlerExecutionChain,ᐺḄCommandḄḄfᵨN᡻X@☢YZhandler[ᘤ5.HandlerExecutionChaingetHandler(HttpServletRequestrequest)throwsException;6.}JḄᐹ3◤⌕MN}N¡ḄMNHandlerExecutionChain,▭E•N᡻XᙠCommand¢£Ḅd᪵N¤4¥ᓫ•NᢝᨵMNInterceptorX[•

27NController;Java<ṹ1.publicclassHandlerExecutionChain{2.3.privateObjecthandler;4.5.privateHandlerlnterceptor[]interceptors;6.7.............8.)}§Handler[Interceptor◤⌕ᡃ#GHHandlerMappingḄ᎛%&¨᝞0ᐹ3ḄSimpleURLHandlerMapping,J©ªḄ᪷¬URL᧜Ḅ®HandlerInterceptor,¯°YZMNw᧜᧜ḄhandlerMap,±◤⌕ᓛ%HttpḄ᎛◤⌕fᵨN⊤@Ḅ´µᩭmᑮ᡻X஺N®ḄᙠIOCᘤᓄSimpleUrlHandlerMappingḄ᎛¶·ᡂ!᪵PyḄ7᪆¹OPᵨᑮmap@Ḅ᧜´µ@Ḅ´µ[beanᦻºḄ´µ»¼Ḅ☢ᐹ3Ḅ®;Java<ṹ1.protectedvoidregisterHandlers(MapurlMap)throwsBeansException{2.if(urlMap.isEmptyO){3.logger.warn("Neither'urlMap*nor'mappings*setonSimpleUrlHandlerMapping");4.)5.else{6.஻@½<ᙠSimpleUrlHandlerMapping$GHḄᡠᨵ᧜ᐗ|7.Iteratorit=urlMap.keySet().iterator();8.while(it.hasNext()){9.஻@¾m%&Ḅurl10.Stringurl=(String)it.next();11.஻@᪷¬urlᙠbeanGH$¾m0Ḅhandler12.Objecthandler=urlMap.get(url);13.//Prependwithslashifnotalreadypresent.14.if(!url.startsWith(T)){15.url=7"+url;16.}17.஻@¿ᵨAbstractHandlerMapping$Ḅ®18.registerHandler(url,handler);19.}20.}21.)ᙠAbstractMappingHandler$Ḅ®<ṹ;Java<ṹ1.protectedvoidregisterHandler(StringurlPath,Objecthandler)throwsBeansException,IllegalStateException{

282.஻ÀÁhandlerMap$¾handler,::ᔲᙠI᪵ḄUri᧜ᐵ3.ObjectmappedHandler=this.handlerMap.get(urlPath);4.if(mappedHandler!=null){5.........6.}7.8.//᝞`ÃᵨbeanĪ᧜dÃᘤ$¾handler9.if(ithis.lazylnitHandlers&&handlerinstanceofString){10.StringhandlerName=(String)handler;11.if(getApplicationContext().isSingleton(handlerName)){12.handler=getApplicationContext().getBean(handlerName);13.)14.)15.஻ᡈὅfᵨhiḄhandler.16.if(urlPath.equals('7*M)){17.setDefaultHandler(handler);18.}19.else{20.஻)url[handlerḄ0ᐵwᑮhandlerMap$Ç21.this.handlerMap.put(urlPath,handler);22.............23.}24.}handlerMapᢝᨵḄMNHashMap,@☢È!ᐹ3Ḅ᧜´µ;Java<ṹ1.privatefinalMaphandlerMap=newHashMap();}SimpleUrlHandlerMapping0HandlerMappingḄ᪵ḄNgetHandler᪷¬ᙠᓄḄ᎛mᑮḄ᧜⊤ᩭÉᡂDispatcherServlet◤⌕Ḅ᡻XJava<ṹ1.publicfinalHandlerExecutionChaingetHandler(HttpServletRequestrequest)throwsException{2.஻@᪷¬request$Ḅpᦪmᑮᐸ0Ḅhandler,ᐹ3ᜐᳮᙠAbstractUrlHandlerMapping$3.Objecthandler=getHandlerlnternal(request);4.஻᝞`ARᑮ0ḄfᵨÍḕḄhandler5.if(handler==null){6.handler=this.defaultHandler;7.}8.//᝞`ÍḕḄbᨵdbÏ!9.if(handler==null){10.returnnull;11.

2912.//᝞`handleÐR•Nᐹ3Ḅhandler,dᡃ#Ñ⌕ᑮIÒᦻ$¾13.if(handlerinstanceofString){14.StringhandlerName=(String)handler;15.handler=getApplicationContext().getBean(handlerName);16.}17.஻ÉᡂMNHandlerExecutionChain,ᐸ$w!ᡃ#ᓛ%EḄhandler[GH¨Ḅᘤᡃ#ᙠHandlerExecutionChain$:ᑮḄd᪵ᢝᨵMNhandler[MNᘤÓ஺18.returnnewHandlerExecutionChain(handler,this.adaptedlnterceptors);19.}ᡃ#::ᐹ3ḄhandlerÔA;Java<ṹ1.protectedObjectgetHandlerlnternal(HttpServletRequestrequest)throwsException{2.஻@.ḄHTTPRequestÖᩭḄpᦪᑖ᪆-mᑮII3Ḅ´µ஺3.StringlookupPath=this.urlPathHelper.getLookupPathForRequest(request);4//a☢᪷¬´µḄ᩵A5.returnlookupHandler(lookupPath,request);6.)7.8.protectedObjectlookupHandler(StringurlPath,HttpServletRequestrequest){9.//᝞`ÙÚÃÙᙠSimpleUrlHandlerMappingḄ᧜⊤$Aᑮdᨬ¨஺10.Objecthandler=this.handlerMap.get(urlPath);11.if(handler==null){12.஻@fᵨᩭ0map$ḄᡠᨵhandleÐᓛ%¿ᵨ!Jre$ḄMatcher¤ᩭ·ᡂᓛ%ᜐᳮ஺13.StringbestPathMatch=null;14.for(Iteratorit=this.handlerMap.keySet().iterator();it.hasNext();){15.StringregisteredPath=(String)it.next();16.if(this.pathMatcher.match(registeredPath,urlPath)&&17.(bestPathMatch==null||bestPathMatch.length()<=registeredPath.Iength()))(18.஻@᪷¬ᓛ%AᑮᨬÜḄMN19.handler=this.handlerMap.get(registeredPath);20.bestPathMatch=registeredPath;21.)22.}23.24.if(handler!=null){25.exposePathWithinMapping(this.pathMatcher.extractPathWithinPattern(bestPathMatch,urlPath),request);26.}27.)28.else{29.exposePathWithinMapping(urlPath,request);

3030.}31.//32.returnhandler;33.}ᡃ#OP:ᑮÝᙠhandlerMapNHashMap$A±ᯠ᝞`ÃAᑮᨬ¨᝞`ARᑮ::RÙ^MatchPatternḄAᡃ#MGÑßmᙠ%&HnaderMappingḄ᎛OP^ANTà%&Ḅᐸ$Ḅᜐᳮᙠ@஺᪵OPáâᙢ:ᑮ᦮NHandlerMappingḄᓄ-Iᡃ#:ᑮ!MNᐹ3Ḅhandler᧜j᪵¶å[ÔAḄ-@ÉᡂMNExecutionchainᩭåᡃ#AᑮḄhandler[ᙠGHbeanḄ᎛GHḄInterceptors.æᡃ#¡ᑮDispatcherServlet,ᓄ·ᡂPy▭Ḅ0webᙠdoService()$ᜐᳮḄᡃ#ç⍝DispatcherServletMNè^ḄServlet:Java<ṹ1.protectedvoiddoService(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2...........3.//@)*ឋ´µÈ4.MapattributesSnapshot=null;5.if(WebUtils.islncludeRequest(request)){6.logger.debugf'Takingsnapshotofrequestattributesbeforeinclude");7.attributesSnapshot=newHashMapO;8.EnumerationattrNames=request.getAttributeNames();9.while(attrNames.hasMoreElements()){10.StringattrName=(String)attrNames.nextElement();11.if(this.cleanupAfterlnclude||attrName.startsWith(DispatcherServlet.class.getName())){12.attributesSnapshot.put(attrName,request.getAttribute(attrName));13.)14.)15.}16.17.//Makeframeworkobjectsavailabletohandlersandviewobjects.18.request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE,getWebApplicationContext());19.request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE,this.localeResolver);20.request.setAttribute(THEME_RESOLVER_ATTRIBUTE,this.themeResolver);21.request.setAttribute(THEME_SOURCE_ATTRIBUTE,getThemeSource());22.23.try{24.஻@f▭Ḅᜐᳮᐭ25.doDispatch(request,response);26.}27.finally{

3128.//Restoretheoriginalattributesnapshot,incaseofaninclude.29.if(attributesSnapshot!=null){30.restoreAttributesAfterlnclude(request,attributesSnapshot);31.)32.}33.}ᡃ#:ᑮ01Ḅᜐᳮ▭EædoDispatch()ᩭ·ᡂḄ-N4êë4¥ᓫì!;Java<ṹ1.protectedvoiddoDispatch(finalHttpServletRequestrequest,HttpServletResponseresponse)throwsException{2.HttpServletRequestprocessedRequest=request;3.஻handlerMapping$mᑮḄ᡻X4.HandlerExecutionChainmappedHandler=null;5.intinterceptorindex=-1;6.7..............8.try{9.//ᡃ#í៉ḄModelAndViewïð!஺10.ModelAndViewmv=null;11.try{12.processedRequest=checkMultipart(request);13.14.//ᡃ#mᑮhandlerḄ15.mappedHandler=getHandler(processedRequest,false);16.if(mappedHandler==null||mappedHandler.getHandler()==null){17.noHandlerFound(processedRequest,response);18.return;19.}20.21.//@¾ð᡻X$ḄInterceptorrᜐᳮ22.if(mappedHandler.getlnterceptors()!=null){23.for(inti=0;i

3233.஻ᙠ᡻handlerñrᵨHandlerAdapterᐜóÔ,handlerḄᔠឋ:RᢥSpringḄ⌕öᑏḄ஺34.HandlerAdapterha=getHandlerAdapter(mappedHandler.getHandler());35.mv=ha.handle(processedRequest,response,mappedHandler.getHandler());36.37.//@¾ð᡻X$ḄInterceptoryᜐᳮ38.if(mappedHandler.getlnterceptors()!=null){39.for(inti=mappedHandler.getlnterceptors().length-1;i>=0;i-){40.Handlerinterceptorinterceptor=mappedHandler.getlnterceptors()[i];41.interceptor.postHandle(processedRequest,response,mappedHandler.getHandler(),mv);42.}43.}44.}45.46.47.48.//Didthehandlerreturnaviewtorender?49.஻@0øÁÉᡂᜐᳮ50.if(mv!=null&&!mv.wasCleared()){51.render(mv,processedRequest,response);52.}53.54.}ᡃ#4áâḄ:ᑮ[MVC᪾úûüýᐵḄ<ṹ᝞᝞þmᑮ[httpý0Ḅ᡻Xj᪵᡻᡻X[j᪵)ᦪ¬ÿᑮ஺ᐜ᪵CommandᡃᩭHandler-☢getHandlerḄṹJavaṹ1.protectedHandlerExecutionChaingetHandler(HttpServletRequestrequest,booleancache)throwsException{2.஻ᙠServletContext᡻!-#▭%&'(ᑮ)Ḅ*᎛ᡃ,)-ᙠServletContext./01஺3.HandlerExecutionChainhandler=4.(HandlerExecutionChain)request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);5.if(handler2null){6.if(Scache){7.request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);8.)9.returnhandler;10.}11.஻34Ḅ565Ḅ*ᙠinitHandlerMappingᢗᐭḄ%ᦻᡠᨵḄHandlerMapping12.Iteratorit=this.handlerMappings.iterator();

3313.while(it.hasNext()){14.HandlerMappinghm=(HandlerMapping)it.next();15............16.஻34#▭handlerḄ<=ᙠ>?HandlerMapping@AḄ᧜C⊤.EFᑮGHIḄhandler17.handler=hm.getHandler(request);18.19.஻ᯠK,handler1ᑮServletContext.0120.if(handler!=null){21.if(cache){22.request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE,handler);23.}24.returnhandler;25.)26.}27.returnnull;28.}᝞MᙠServletContextNOhandlerᑣQRST#▭%3?handler0U/%(ᜐᳮḄXM-Y⌕ᨵ&'(,3?handler-ᑮServletContext᝞MᙠServletContext[\ᑮhandler,]^<ᢝᨵḄHandlerMapping`ᡂ'?,ᡃᑮ)c5deᢝᨵḄᡠᨵḄhandlerMapping,fgNOhi\j'?kᙠhiḄ*᎛lNOᢣhnoQᑮ[ᑮ&'?ᯠKSpᐜ[ᑮ'?handlerMappingᯠK^<3?handlerMappingSq'?᡻!4☢ᒹs/ᨬuḄHandlervᡃhiḄ,wxḄInterceptor஺ᐹzḄᡃNO{ὃ%☢ḄSimplellrlHandlerMappingḄṹᑖ᪆⍝getHandler᪵ᑮ'?HandlerExecutionChainḄ஺ijHandlerExecutionChainOKᡃ^

343publicbooleansupports(Objecthandler){4.return(handlerinstanceofController);5.)6.7.}ᓫḄᑨ'handler\#/ControllerR஺3lz/'ᦻ.Ḅᑴ஺ᡃTᑮDispatcherServletᑮṹJavaṹ1.mv=ha.handle(processedRequest,response,mappedHandler.getHandler());3?handleḄᐹzᵨdCommand4ḄCommand.execute஺;ᳮᡠdᯠḄST'?ModelAndView,¡.☢'?View.ᜐᳮḄ<=Javaṹ1.if(mv!=null&&!mv.wasCleared()){2.render(mv,processedRequest,response);3.)ᵨḄrender£Javaṹ1.protectedvoidrender(ModelAndViewmv,HttpServletRequestrequest,HttpServletResponseresponse)2.throwsException{response.setLocale(locale);3.4.Viewview=null;5.஻34,¤¥Ḅ-ᑮModelAndView஺6.if(!mv.hasView()){7.mv.setViewName(getDefaultViewName(request));8.)9.10.if(mv.isReference()){11.஻34¦§.¨᪆12.view=resolveViewName(mv.getViewName(),mv.getModellnternal(),locale,request);13.............14.)15.else{16.஻ᨵN©ᙠModelAndView4ª«QRᒹsTView]ᡃQR¬ᵨ஺17.view=mv.getView();18..............19.}20.21.஻ᑮᐹzḄViewOKᡃᵨ)ᩭ`ᡂ஺22.view.render(mv.getModellnternal(),request,response);23.}

35᦮?<=ᡃᑮᐜᙠModelAndView¯[Ḅ°±¦᝞M[\ᑮ]¬ᵨ²ḕḄ᝞M©´[ᑮḄ¦§]k.¨᪆ᑮ#▭Ḅ◤⌕¬ᵨḄ஺¶ᨵ'N©ᙠModelAndViewª«ᒹs/#▭Ḅ3?NOQR¬ᵨḄ஺\·᪵ᑮ'?OK^<ᵨḄrenderᩭ¸ᡂᦪºḄ»¼<=ᡃNOᐹzḄJstIView᪵#ḄᡃᙠJstIViewḄ½᱄¿Abstractview[ᑮrender£Javaṹ1.publicvoidrender(Mapmodel,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2.……3.//34,ᡠᨵḄᐵÁÂÃᦈÅᑮ'?Map44.MapmergedModel=newHashMap(this.staticAttributes.size()+(model!=null?model.size0:0));5.mergedModel.putAII(this.staticAttributes);6.if(model!=null){7.mergedModel.putAII(model);8.}9.10.//ExposeRequestcontext?11.if(this.requestContextAttribute!=null){12.mergedModel.put(this.requestContextAttribute,createRequestContext(request,mergedModel));13.}14.஻3#▭ḄÆÇᦪºᑮḄᵨ஺15.renderMergedOutputModel(mergedModel,request,response);16.}ȨᑏḄÊËÌ/ᐜ,ᡠᨵḄᦪºÇ.᦮ᔠ-ᑮ•?Map-mergedModel4ᯠKᵨrenderMergedOutputModel();i>[^renderMergedOutputModel'?Í£kḄ#ᙠInternalResourceViewlJstIViewḄ᱄¿:Javaṹ1.protectedvoidrenderMergedOutputModel(2.Mapmodel,HttpServletRequestrequest,HttpServletResponseresponse)throwsException(3.4.//Exposethemodelobjectasrequestattributes.5.exposeModelAsRequestAttributes(model,request);6.7.//Exposehelpersasrequestattributes,ifany.8.exposeHelpers(request);9.10.஻34ᑮInternalResourcehiḄᑁÐÑÒÓÔ஺11.StringdispatcherPath=prepareForRendering(request,response);12.

3613.஻34,GHÕÖᑮe☢ᑮḄᑁÐÑÒÓÔ஺14.RequestDispatcherrd=request.getRequestDispatcher(dispatcherPath);15.if(rd==null){16.thrownewServletException(17."CouldnotgetRequestDispatcherfor["+getUrl()+"]:checkthatthisfileexistswithinyourWAR");18.}19✌ᐜÇᦪº.ᜐᳮexposeModelAsRequestAttributesᙠAbstractview#Ḅ3?£,ModelAndViewḄÇᦪºvᐸkrequestᦪºÙÙ-ᑮServletContextd3᪵᦮?Çᦪº^

3710.}11.12.protectedvoidexposeHelpers(HttpServletRequestrequest)throwsException{13.JstlUtils.exposeLocalizationContext(request,this.jstlAwareMessageSource);14.)15.16.}ᙠJstlUtilsᒹs/ᐸkßàjstlᱯâḄᦪºᜐᳮvã஺<=\Êäåᡃᙠᙠæ4/åᕣᕣᡃèè¸ᡂḄéMVCViewḄrender,InternalResourceViewḄrender<=êᓫë¸ᡂ'?ÑÒḄìhᔣᜐᳮ஺◤⌕îḄᑮ#▭viewḄinternaïesourceÓÔᯠKÕÖᑮ]?ÑÒ஺᪵ᑮÑÒḄÓÔᕖ^<ᵨJavaṹ1.protectedStringprepareForRendering(HttpServletRequestrequest,HttpServletResponseresponse)2.throwsException{3.4.returngetUrl();]3?urlᙠæ4`ᡂᕖåᡃᙠViewᐵḄṹñᨵ[ᑮ#▭%kᙠViewRosolveḄ*᎛`ᡂ/ᙠUrlBasedViewResolverJavaṹ1.protectedAbstractUrlBasedViewbuildView(StringviewName)throwsException{2.AbstractUrlBasedViewview=(AbstractUrlBasedView)Beanlltils.instantiateClass(getViewCIass());3.view.setllrl(getPrefix()+viewName+getSuffix());4.StringcontentType=getContentType();5.if(contentType!=null){6.view.setContentType(contentType);7.}8.view.setRequestContextAttribute(getRequestContextAttribute());9.view.setAttributesMap(getAttributesMap());10.returnview;11.)34`ᡂViewḄᙢ£óᯠl,`ᡂḄurlvᐸk•ôvviewᐵḄõឋlö/஺]3?ViewResolve÷ø*᎛ùᵨḄᕖåúúᡃ3᪵û⌕TᑮDispatcherServletüýᙠDispatcherServletJavaṹ1.protectedvoidrender(ModelAndViewmv,HttpServletRequestrequest,HttpServletResponseresponse)2.throwsException{3.4.............

385.Viewview=null;6.7.//34ã¦g¤¥Ḅ¦§8.if(!mv.hasView()){9.mv.setViewName(getDefaultViewName(request));10.}11.12.if(mv.isReferenceO){13.஻34¦.¨᪆ᙠ¨᪆Ḅ<=᪷º◤⌕`ᡂ#▭◤⌕Ḅ஺14.view=resolveViewName(mv.getViewName(),mv.getModellnternal(),locale,request);15...............16.}1718.)☢¦.¨᪆Ḅᐹz<=Javaṹ1.protectedViewresolveViewName(StringviewName,Mapmodel,Localelocale,HttpServletRequestrequest)2.throwsException{3.஻ᡃᨵN©\j'?¨᪆ᘤ4.for(Iteratorit=this.vlewResolvers.iterator();it.hasNext();){5.ViewResolverviewResolver=(ViewResolver)it.next();6.஻U!᪆ᘤ᪆ᡂḄ஺7.Viewview=viewResolver.resolveViewName(viewName,locale);8.if(view!=null){9.returnview;10.}11.)12.returnnull;13.}ᵨᐹḄViewResolverḄ᪆-◀ᓫḄ᪆᜜!"#᪷%ᡃ'Ḅ⌕)ᡂTᡃ'*▭◤⌕Ḅ-஺ᐹḄviewResolverᙠbean/0ᦻ23/045ᙠinitViewResolver()67389:ᓄᑮviewResolver=>3!ᡃ'??ᐹḄInternalResourceViewResolver@᪵ᜐᳮḄᡂV-ḄDresolveViewNameḄᵨEFᙠAbstractCachingViewResolver3!JavaGṹ1.publicViewresolveViewName(StringviewName,Localelocale)throwsException{2.஻᝞JKᨵᡭNOPQR!STU◤⌕Ḅ3.if(!isCache()){4.logger.warn(MViewcachingisSWITCHEDOFF-DEVELOPMENTSETTINGONLY:Thiscanseverelyimpairperformance")V5.returncreateView(viewName,locale);

396.7.else{8.ObjectcacheKey=getCacheKey(viewName,locale);9.//Nosynchronization,aswecanlivewithoccasionaldoublecaching.10.synchronized(this.viewCache){11.஻WXOPḄ-12.Viewview=(View)this.viewCache.get(cacheKey);13.if(view==null){14.஻᝞JᙠOP3KᨵXᑮ!TUYZ[TUḄ\ᑮOP3]15.view=createView(viewName,locale);16.this.viewCache.put(cacheKey,view);17.................18.}19.returnview;20.}21.)22.}ᐵ_`createView(),loadView(),buildView()Ḅᐵa!ᡃ'??EclipseḄcallhiearchyᯠcᡃ'dᑮview.renderet1fᡂᦪ%ḄᨬihttpResponseḄᑏᐭ!l᝞ᙠAbstractExcelView3Ḅ*mDJavaGṹ1.protectedfinalvoidrenderMergedOutputModel(2.Mapmodel,HttpServletRequestrequest,HttpServletResponseresponse)throwsExcept!on{3...............4.//response.setContentLength(workbook.getBytes().length);5.response.setContentType(getContentType());6.ServletOutputStreamout=response.getOutputStream();7.workbook.write(out);8.out.flush();9.)᪵noᡃ'p☢Ḅᑖ᪆•tuᩭ:DispatcherServletᙠ᪆Ḅ5᎛n᪷%⌕)ᡂ-!ᒹzᙠInternalResourceView3◤⌕{ᵨḄurloᐸ}ᔜoHTTPresponseᐵḄឋᑏᢝᙠᡂḄ-3!ᯠcnᵨ-Ḅrenderᩭfᡂᦪ%Ḅ஺n᦮ZSpringWebMVC᪾Ḅᜧt!᦮ZMVCᵫDispatcherServletᩭᑴ஺MVCḄᐵᒹzDRᑮhandlerḄ᧜ᐵao@᪵᪷%)ᦪᑮḄhandler,ᙠSpring3!ᵫhandlerMapping᡻ᩭfᡂḄ!ᐹḄ᧜ᐵaᡃ'ᙠbean/0ᦻ23/0ᙠHandlerMappingᐭ¡ᦻḄ5᎛n8R¢஺ᯠcDispatcherServletᵨHandlerMappingᩭᑮḄ᡻!ᨬcᩭmE£ᦪ%!¤ᡃ'⌕¥¦Ḅ-ᙠ᪆Ḅ5᎛ᡂR¢Ḅ஺`§¨᪶ª«ḄHanderMapping,ViewResolver,View,HandlerḄ¬®§*mMVCḄ¯°஺

40¡☢ᡃ'ᩭ??SpringḄAOPḄY`ᐵGṹ@±ᑮProxyḄ!²ᡃ'ᡃ'ᐜ??AOPoSpringAOPḄY`´µᭆ·DAdviceD¸!ᑴ/ᙠ¹º»¼±!ᙠSping3!}½⌕¾¿SpringÀÁ67ᵨ¥ᐭḄÂ᜜Ḅ¨!SpringÃÄḄ¸«£ᨵDbeforeadvice,AfterReturningAdvice,ThrowAdvice,MethodBeforeAdvice,`SpringAOP/0ḄÅ«!ᐹḄƧ*m◤⌕ᵨᡝÈᩭfᡂ஺Pointcut:ᑗº!ᐸÊ/YZadviceËᵨ_ÌZ¹º!Ín◤⌕ÎᐭÂ᜜ᜐᳮḄᙢ6ḄÐᔠ!Ò᝞!8ÓZadvice§¨Ô᪗ḄYÖ67஺SpringpointcutצᕡḼ᪗67!ÚÛ⌱ÝYÖ67ᵨ§¨pointcut,SpringÃÄᐹḄᑗºᩭÞᵨᡝ{ᵨ!l᝞ßᑣ⊤âãᑗºJdkRegexpMethodPointcutßᑣ⊤âã67ᓛ!ᐸ{ᵨAbstractJdkRegexpMethodPointcut3ḄMethodMatcherSÅḄ*mᩭfᡂpointcut¯°DJavaGṹ1.publicfinalbooleanmatches(Methodmethod,Classtargetclass){2.஻\ᑮ67Ḅᐰ3.Stringpatt=method.getDeclaringClass().getName()++method.getName();4.for(inti=0;i

41Ḽᡃ'nÚÛProxyFactoryBeanᩭRᡃ'ḄGᳮ-o6☢¨!ᙠProxyFactoryBean3ᨵinterceptorNamesᩭRñò/0¢Ḅ¸ᘤ-advisor,óᯠḄô»interceptNames,¤*▭Äᡃ'RadvisorḄᙢ6!ᐹḄGᳮ*mJDKḄProxyᡈὅCGL÷ᩭfᡂ஺ø¨ProxyFactoryBeanYZFactoryBean,ᙠProxyFactoryBean3ᡃ'getObject()ÚÛùUGᳮ-DJavaGṹ1.publicObjectgetObject()throwsBeansException{2.஻9:ᓄ¸ᘤ3.initializeAdvisorChain();4.if(isSingleton()){5.஻᪷%/0◤⌕ᡂᓫ2ḄProxy6.returngetSingletonInstance();7.)8.else{9............10.஻᪷%/0◤⌕ᡂPrototype«£ḄProxy11.returnnewPrototypelnstance();12.)13.)ᡃ'??@᪵ᡂᓫ2ḄGᳮ-DJavaGṹ1.privatesynchronizedObjectgetSingletonlnstance(){2.if(this.singletonlnstance==null){3.this.targetSource=freshTargetSource();4.if(this.autodetectlnterfaces&&getProxiedlnterfaces().length==0&&lisProxyTargetClass()){5.஻QRGᳮ-ḄÅ6.setlnterfaces(ClassUtils.getAlllnterfacesForClass(this.targetSource.getTargetClass()));7.)8.//Eagerlyinitializethesharedsingletoninstance.9.super.setFrozen(this.freezeProxy);10.//¥¦Ḅ67{ᵨProxyFactoryᩭᡂᡃ'◤⌕ḄProxy11.this.singletonlnstance=getProxy(createAopProxy());12.//Wemustlistentosuperclassadvicechangeeventstorecachethesingleton13.//instanceifnecessary.14.addListener(tMs);15.}16.returnthis.singletonlnstance;17.}18.19.஻{ᵨcreateAopProxy\dḄAopProxyᩭᑮGᳮ-஺

4220.protectedObjectgetProxy(AopProxyaopProxy){21.returnaopProxy.getProxy(this.beanClassLoader);22.}ProxyFactoryBeanḄ᱄«AdvisedSupport,Spring{ᵨAopProxyÅ[AOPGᳮḄ*mû᪾Ḅᐸ}üᑖᑖýNᩭDᙠAdvisedSupport3᪵Ḅ6ãᩭᑮAopProxy,ëᯠ◤⌕ᑮAopProxyFactoryḄþÿ-☢ᡃᑮSpringᡃḄ,ᩭᡃḄJDKᡈὅcglibᑮᡃ⌕ḄᳮJavaṹ1.protectedsynchronizedAopProxycreateAopProxy(){2.if(Ithis.isActive){3.activate();4.}5.returngetAopProxyFactory().createAopProxy(this);6.}ᙠProxyConfig"ᵨḄAopProxyFactory$%&'Javaṹ1.஻*+DefaultAopProxyFactory,Springᵨᩭ-ᡂAopProxyḄᙢ02.஻1ᯠ%3ᒹ5JDK6Cglib789஺3.privatetransientAopProxyFactoryaopProxyFactory=newDefaultAopProxyFactory();ᐸᙠDefaidtAopProxyFactory,*᪵-ᡂAopProxyḄJavaṹ1.publicAopProxycreateAopProxy(AdvisedSupportadvisedSupport)throwsAopConfigException{2.஻✌ᐜὃ⇋"ᵨcglibᩭᳮA01ᯠ᝞CDA11᪗F,GHḄIḄJ3.if(advisedSupport.isOptimize()||advisedSupport.isProxyTargetClass()||4.advisedSupport.getProxiedlnterfaces().length==0){5.஻*KᑨM᝞CFNᙠcglibO0PGQRST஺6.if(IcglibAvailable){7.thrownewAopConfigException(8."CannotproxytargetclassbecauseCGLIB2isnotavailable.'1+9."AddCGLIBtotheclasspathorspecifyproxyinterfaces.'1);10.}11.஻*K"ᵨCglibᩭ-ᡂProxy,᝞CtargetF,GHḄḄJ0UVcglibIWḄAopProxy12.returnCglibProxyFactory.createCglibProxy(advisedSupport);13.}14.else{15.//*K"ᵨJDKᩭ-ᡂProxy,UVJDKIWḄAopProxy16.returnnewJdkDynamicAopProxy(advisedSupport);17.)18.}

43Y,ᡃZ[\ᑮᐸḄᳮ[\ᵫJDKᡈὅCglibᩭ-ᡂ0ᡃᑮJdkDynamicAopProxyI6Cglib2AopProxy^Ḅ,AopProxyḄGH0ᙠJdkDynamicAopProxyᡃ[\ᑮProxy,_᪵-ᡂḄJavaṹ1.publicObjectgetProxy(ClassLoaderclassLoader){2.if(logger.isDebugEnabled()){3.Classtargetclass=this.advised.getTargetSource().getTargetClass();4.Iogger.debug(࠷reatingJDKdynamicproxy"+5.(targetclass!=null?"for["+targetClass.getName()+T:6.)7.Class[]proxiedInterfaces=AopProxyUtils.completeProxiedlnterfaces(this.advised);8.findDefinedEqualsAndHashCodeMethods(proxiedlnterfaces);9.஻*KᡃaᵨJDKProxyᩭ-ᡂ◤⌕ḄProxyc10.returnProxy.newProxylnstance(classLoader,proxiedlnterfaces,this);11.)*᪵ᵨProxyᒹdtargetef0ghProxyFactoryBeanᑮᐸiḄaᵨZjProxykl%0ProxyFactoryBeanḄgetObject஺iᑮḄ▭n,o+Proxy%0ᡃḄtargetpqjrd%஺ProxyFactoryBean*+sᔆbeanu0ᐸ-vRᩭḄ,rd%w᪗Ḅᳮ஺ᡃSpringḄxyᜐᳮḄṹ0"ᵨSpring{ᳮxyᨵ}~9697890}~9xyᜐᳮghAOPḄxᱥ{ᳮṹ☢rdᩭᔣᐭᑮyṹ0"xy{ᳮṹ6yṹ஺ᙠ*89ᡃᔠloCᘤ6SpirngpᨵḄFactoryBeanᩭxy{ᳮឋ0᝞0◞஺ᐸᨬᓫḄ9Z,ghTransactionProxyFactoryBeanᩭ}~9xᱥᙠ᦮+¡ṹᑖ᪆0ᡃ[\ᜧ¥[\ᑮSpring}~9xᱥ{ᳮᨵ*¦§+¨ᑖ*ᙠnªᦻ41ḄឋḄᜐᳮ0*K¬ḄI,TransactionAttributeSourceAdvisor,*,o+g®ᘤ0ᵨ3ᩭឋ¯ᜐᳮ0ឋ°±²ᙠTransactionAttributeᩭ"ᵨ0*³ឋḄᜐᳮ´´,6ᑗᐭ¶Ḅᜐᳮ,ᔠ·ᩭḄ஺ឋḄᜐᳮ²ᙠITransactionAttributesource¸ᡂ஺*¹ºxᱥḄh0*+h,»ᡲ½ᐹ¿Ḅxᱥ{ᳮᘤᩭ¹ºḄ0ÀSpringghTransactionstatusᩭ⌴ÂᐵḄ°±஺*xᱥḄᜐᳮghÂᐵ°±ḄᑨMᩭ»ᡲ½ᐹ¿Ḅxᱥ{ᳮᘤ¸ᡂ஺ᡃª☢ᐹ¿Ḅ0ftTransactionFactoryBean+Javaṹ1.publicclassTransactionProxyFactoryBeanextendsAbstractSingletonProxyFactoryBean2.implementsFactoryBean,BeanFactoryAware{3.஻*K,Springxyᜐᳮ"ᵨḄAOPᡚᘤ0Ærd%SpringxyᜐᳮḄÇᩭÈᢝÊ~9xyᜐᳮḄ4.privatefinalTransactionInterceptortransactioninterceptor=newTransactionlnterceptor();5.6.privatePointcutpointcut;7.8.஻*KSpringTransactionManagerËᐭᑮTransactioninterceptor'I'i-

449.publicvoidsetTransactionManager(PlatformTransactionManagertransactionManager){10.this.transactionlnterceptor.setTransactionManager(transactionManager);11.)12.13.஻*KᙠbeanᦻÌÍᑮḄxy{ᳮḄឋ°±ËᐭᑮTransactionInterceptor14.publicvoidsetTransactionAttributes(PropertiestransactionAttributes){15.this.transactionlnterceptor.setTransactionAttributes(transactionAttributes);16.}17.18Æḕᶍ%ᐸÐo³i……19.20.஻*K¹ºSpringAOPxyᜐᳮḄAdvisor21.protectedObjectcreateMainlnterceptor(){22.this.transactionlnterceptor.afterPropertiesSet();23.if(this.pointcut!=null){24.஻*K"ᵨÒÓḄg®ᘤ25.returnnewDefaultPointcutAdvisor(this.pointcut,this.transactionlnterceptor);26.}27.else{28.//"ᵨn☢&'ÔḄTransactioninterceptorklᘤ0DA"ᵨTransactionAttributeSourceAdvisor29.returnnewTransactionAttributeSourceAdvisor(this.transactionlnterceptor);30.}31.}32.}ÕÖ¦A᎛SpringḄTransactioninterceptorjËᐭᑮSpringAOPᡂAdvisorḄo¨ᑖᕖÙᡃᑮᙠTransactionProxyFactoryBean0*+iᙠIOCÚÛᓄbeanḄA᎛j᡻Javaṹ1.publicvoidafterPropertiesSet(){2.............3.//TransactionProxyFactoryBean▭n"ᵨProxyFactory¸ᡂAOPḄÞßàá஺4.ProxyFactoryproxyFactory=newProxyFactory();5.6.if(this.preinterceptors!=null){7.for(inti=0;i

4515.஻ᵫ3ᩭæço+adviceḄè⊤0gh*+è⊤Ḅêᑤᦋᩭíᡃ᦮+g®ᘤḄêᑤᦋî஺16.proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainlnterceptor()));17.18.if(this.postInterceptors!=null){19.for(inti=0;i

46ñ᧜%ÞßḄSpringAOPḄ&'h0ᐸpointcut6advice^pq&'Ô0DAóghg®ᘤᑮProxyFactoryã%஺ª☢ôᡃVõijTransactionProxyFactoryBean•t1##TransactionAttributesourceAdvisor,_᪵&'Ḅ0*᪵ᡃ[\ᳮᐹ¿Ḅឋ,_᪵·ᵨ0*Kᡃᑖ᪆oªITransactionAttributeSourceAdvisor:Javaṹ1.publicclassTransactionAttributeSourceAdvisorextendsAbstractPointcutAdvisor{2.஻6ᐸÐAdvisoro᪵0D᪵◤⌕&'AOPḄᵨᑮḄInterceptor6Pointcut3.//Interceptor"ᵨᩭḄTransactioninterceptor4.஻Ypointcut,*U!&'%…+ᑁ¨I0ä÷ª☢Ḅṹ5.privateTransactioninterceptortransactioninterceptor;6.7.privatefinalTransactionAttributeSourcePointcutpointcut=newTransactionAttributesourcePointcut();8.9.

4710.஻&'ḄPointcutᑁ¨I11.privateclassTransactionAttributeSourcePointcutextendsStaticMethodMatcherPointcutimplementsSerializable{12..........13.஻iᓛḄ0"ᵨ%TransactionAttributesourceI14.publicbooleanmatches(Methodmethod,Classtargetclass){15.TransactionAttributeSourcetas=getTransactionAttributeSource();16.஻*K"ᵨTransactionAttributeSourceᩭឋᜐᳮ17.return(tas!=null&&tas.getTransactionAttribute(method,targetclass)!=null);18.}19.........ḕᶍ%equal,hashcode,tostringḄṹ20.}*Kᡃឋ¯,_᪵jÍᐭḄAbstractFallbackTransactionAttributeSourceùúᐹ¿ḄឋÍᐭûy0ᡃ[\ᨵ78Íᐭ90᝞annotation6PG.ᡃ☢PGḄÍᐭ90ᙠSpringDAÍᐭḄឋ¯%ýNᜐᳮ0*,o+decoratorþ9Javaṹ1.publicfinalTransactionAttributegetTransactionAttribute(Methodmethod,Classtargetclass){2.஻*KᐜÿᔥᨵᨵᳮḄឋ,᝞ᨵTransactionAttribute3.ObjectcacheKey=getCacheKey(method,targetclass);4.Objectcached=this.cache.get(cacheKey);5.if(cached!=null){6.if(cached==NULL_TRANSACTION_ATTRIBUTE){7.returnnull;8.)9.else{10.return(TransactionAttribute)cached;11.)12.)13.else{14.//᪗!Ḅ"#ᩭ%&ឋ15.TransactionAttributetxAtt=computeTransactionAttribute(method,targetclass);16.஻(ᑮḄឋᑮ*+,-./01|17.if(txAtt==null){18.this.cache.put(cacheKey,NULL_TRANSACTION_ATTRIBUTE);19.}20.else{21.........................22.this.cache.put(cacheKey,txAtt);23.}24.returntxAtt;25.}26.}

483ញ*5ᩈḄᜐᳮᙠcomputeTransactionAttribute()9Java:ṹ1.privateTransactionAttributecomputeTransactionAttribute(Methodmethod,Classtargetclass){2.஻<=>?>public3.if(allowPublicMethodsOnly()&&jModifier.isPublic(method.getModifiers())){4.returnnull;5.}6.7.MethodspecificMethod=AopUtils.getMostSpecificMethod(method,targetclass);8.9.//Firsttryisthemethodinthetargetclass.10.TransactionAttributetxAtt=findTransactionAttribute(findAIIAttributes(specificMethod));11.if(txAtt!=null){12.returntxAtt;13.}14.15.//Secondtryisthetransactionattributeonthetargetclass.16.txAtt=findTransactionAttnbute(findAIIAttributes(specificMethod.getDeclaringClass()));17.if(txAtt!=null){18.returntxAtt;19.}20.21.if(specificMethod!=method){22.//Fallbackistolookattheoriginalmethod.23.txAtt=findTransactionAttribute(findAIIAttributes(method));24.if(txAtt•=null){25.returntxAtt;26.}27.//Lastfallbackistheclassoftheoriginalmethod.28.returnfindTransactionAttribute(findAIIAttributes(method.getDeclaringClass()));29.}30.returnnull;31.}@ABᑡḄDEᡃG-.findTransactionAttribute()HᵨfindAIIAttribute()JijTransactionAttributeḄ!*᝞KLḄ>null,MNO?>ᡃG◤⌕ᜐᳮḄ஺ᙠSᡂ(◤⌕ḄUᘤWᑮProxyFactoryXḄ5ẠZ*ᡃG[[ᐹ]Ḅ[ᜐᳮ:ṹ^᪵`aᵨ*ᙠTransactioninterceptor9Java:ṹ1.publicObjectinvoke(finalMethodinvocationinvocation)throwsThrowable{2.஻ᑮ᪗!3.Classtargetclass=(invocation.getThis()!=null?invocation.getThis().getClass():null);

494.5.஻b᪵Ḅᑨd>ᔲfgᑮTransactionAttrlbuteᩭhi>ᔲjklmᜐᳮ*ᨵ-fOឋn@o*6.஻ᐹ]-.pὃZ☢getTransactionAttributeḄᑖ᪆*b᪵>TransactionAttributeSource7.finalTransactionAttributetxAttr=8.getTransactionAttributeSource().getTransactionAttribute(invocation.getMethod(),targetClass);9.finalStringjoinpointidentification=methodldentification(invocation.getMethod());10.11.஻ᑨdᡃGuᵨvwxTransactionManager12.if(txAttr==null||!(getTransactionManager()instanceofCallbackPreferringPlatformTransactionManager)){13.//yz,b{(yz|ᑮḄ"#}ᑮTransactioninfoX14.Transactioninfotxlnfo=createTransactionIfNecessary(txAttr,joinpointidentification);15.ObjectretVal=null;16.try{17.retVal=invocation.proceed();18.}19.catch(Throwableex){20.//targetinvocationexception21.completeTransactionAfterThrowing(txlnfo,ex);22.throwex;23.}24.finally{25.cleanupTransactionlnfo(txlnfo);26.}27.commitTransactionAfterReturning(txlnfo);28.returnretVal;29.}30.31.else{32.//uᵨḄ>Springi~ḄPlatformTransactionManagerb{vLH0*ᡃGᐸLHᦪSᡂᜐᳮ*ᡃGuᵨ|ᜐᳮA᪵஺33.try{34.Objectresult=((CallbackPreferringPlatformTransactionManager)getTransactionManager()).execute(txAttr,35.newTransactionCallback(){36.publicObjectdolnTransaction(TransactionStatusstatus){37.஻b᪵Ḅ◤⌕ATransactonInfo38.Transactioninfotxlnfo=prepareTransactionlnfo(txAttr,joinpointidentification,status);39.try{40.returninvocation.proceed();

5041.42.…ḕXvᜐᳮ"#Ḅᳮ:ṹ43.44.............45.}46.}☢ᑮḄyz*ᡃG-.ᙠTransactionAspectsupportḄᳮ:ṹ9Java:ṹ1.protectedTransactioninfocreateTransactionIfNecessary(2.TransactionAttributetxAttr,finalStringjoinpointidentification){3.4.//Ifnonamespecified,applymethodidentificationastransactionname.5.if(txAttr!=null&&txAttr.getName()==null){6.txAttr=newDelegating?ransactionAttribute(txAttr){7.publicStringgetName(){8.returnjoinpointidentification;9.)10.};11.)12.13.Transactionstatusstatus=null;14.if(txAttr!=null){15.//uᵨvᡃGi~Ḅ"#,ᨵᳮᘤᩭyz,b{KLTransactioninfo16.status=getTransactionManager().getTransaction(txAttr);17.)18.returnprepare!ransactionlnfo(txAttr,joinpointidentification,status);19.}✌ᐜTransactionManagerᑮ◤⌕Ḅ*Ḅyz᪷ᡃGi~Ḅhi*ᙠAbstractTransactionManager•᪗Ḅyz|*jᯠyzwx᪵Ḅ>◤⌕ᐹ]ḄPlatformTransactionManagerᩭhi*vyzḄ¡9Java:ṹ1.publicfinalTransactionstatusgetTransaction(TransactionDefinitiondefinition)throwsTransactionException{2.Objecttransaction=doGetTransaction();3.……4.5.if(definition==null){6.஻᝞9"#ᨵo*ᡃGuᵨSpring¢£Ḅ7.definition=newDefauItTransactionDefinition();8.)9.

5110.if(isExistingTransaction(transaction)){11.//Existingtransactionfound->checkpropagationbehaviortofindouthowtobehave.12.returnhandleExistingTransaction(definition,transaction,debugEnabled);13.)14.15.//Checkdefinitionsettingsfornewtransaction.16.஻+☢>uᵨ"#ᩭyzᡃG◤⌕Ḅ:;¦᝞§¨©ªb«ª¬17.஻ᨬ®(yz|Ḅ"#ᦈ°`ᩭ}ᑮTransactionstatusK±18.if(definition.getTimeout()checkpropagationbehaviortofindouthowtobehave.23.if(definition.getPropagationBehavior()==TransactionDefinition.PROPAGATION_MANDATORY){24.thrownewIHegalTransactionStateException(25."Transactionpropagation'mandatory'butnoexistingtransactionfound")26.}27.elseif(definition.getPropagationBehavior()==TransactionDefinition.PROPAGATION_REQUIRED||28.definition.getPropagationBehavior()==TransactionDefinition.PROPAGATION_REQUIRES_NEW||29.definition.getPropagationBehavior()==TransactionDefinition.PROPAGATION_NESTED){30.஻>ᳮᘤyzḄᙢ*³´yz|ᑮḄ"#}ᑮTransactionstatusX*ᒹ¶yzᩭḄ31.doBegin(transaction,definition);32.booleannewSynchronization=(getTransactionSynchronization()!=SYNCHRONIZATION_NEVER);33.returnnewTransactionStatus(definition,transaction,true,newSynchronization,debugEnabled,null);34.}35.else{36.booleannewSynchronization=(getTransactionSynchronization()==SYNCHRONIZATION_ALWAYS);37.returnnewTransactionStatus(definition,null,false,newSynchronization,debugEnabled,null);38.}39.}0ḼHᵨprepareTransactionlnfoSᡂyzḄᜓ*yz|ᑮḄ"#¹ᙠTransactionInfo!lm§⌴b{("#jk»|¼iJava:ṹ

521.protectedTransactioninfoprepareTransactionlnfo(2.TransactionAttributetxAttr,Stringjoinpointidentification,Transactionstatusstatus){3.4.Transactioninfotxlnfo=newTransactionlnfo(txAttr,joinpointidentification);5.if(txAttr!=null){6.…7.஻b᪵Ḅ◤⌕(ᙠgetTransaction½JijḄTransactionstatus}ᑮTransactioninfoᩭ஺8.txlnfo.newTransactionStatus(status);9.)10.else{1112.)13.14.//¼iyz"#ᑮjk»|15.txlnfo.bindToThread();16.returntxlnfo;17.)´yzḄ"#K¾*ᯠ®[ᑮᐸ¿Ḅᳮ:ṹ9Java:ṹ1.protectedvoidcommitTransactionAfterReturning(Transactionlnfotxlnfo){2.if(txlnfo!=null&&txlnfo.hasTransaction()){3.if(logger.isDebugEnabled()){4.Iogger.debug("lnvokingcommitfortransactionon"+txlnfo.getJoinpointldentification());5.}6.this.transactionManager.commit(txlnfo.getTransactionStatus());7.}8.)transactionManagerlmᜐᳮ*ᒹ¶ÀÁḄÂÃ*ᐹ]Ḅᳮᘤᵫᵨᡝ|ÆÇi஺Java:ṹ1.protectedvoidcompleteTransactionAfterThrowing(Transactionlnfotxlnfo,Throwableex){2.if(txlnfo!=null&&txlnfo.hasTransaction()){3.if(txlnfo.transactionAttribute.rollbackOn(ex)){4...................5.try{6.this.transactionManager.rollback(txlnfo.getTransactionStatus());7.}8.......................9.}10.else{11.

5312.try(13.this.transactionManager.commit(txlnfo.getTransactionStatus());14.)15.......................16.}17.18.protectedvoidcommitTransactionAfterReturning(Transactionlnfotxlnfo){19.if(txlnfo!=null&&txlnfo.hasTransaction()){20.……21.this.transactionManager.commit(txlnfo.getTransactionStatus());22.}23.}Spring.Z:ṹtransactionManagerlmᜐᳮḄ|lmvAOPᒹÈ*ᑮᡃG[ᑮÉvÊËᡝÌNḄᜐᳮ*Spring>ÍvÎÏÐaḄ஺᝞Muᵨ|ᜐᳮ*|ᐸ¦ÑÒ*ᡃG-.pὃÓḄÔÕ9Java:ṹ1.TransactionDefinitiontd=newDefaultTransactionDefinition();2.Transactionstatusstatus=transactionManager.getTransaction(td);3.try{4.……஻>ᡃGḄÖ5.Jcatch(ApplicationExceptione){6.transactionManager.rollback(status);7.throwe8.}9.transactionManager.commit(status);10ᡃG[ᑮ⌱v¢£ḄDefaultTransactionDefinition,b{ᙠyzᱥḄ|ᑮTransactionstatusᯠ®/0HᵨᳮᘤḄÙᐵfSᡂᜐᳮ஺ÌNᜐᳮÛb᪵vÜÝḄ|*Þ>ßÉàᵨvÌNḄ*◤⌕áWឋḄâᜐᳮ*³ã◤⌕(᦮|᦮ᔠᑮSpringAOP᪾çloCèᘤXḄ|஺+☢ᡃG⌱Aᐹ]ḄtransactionManager-DataSourceTransactionManagerᩭ[[ᐸᜐᳮḄ9b᪵ḄuᵨAbstractPlatformTransactionManageruᵨ¡*éê]vᐹ]ëìÙᐵḄᳮᘤíaḄîÈ*¦᝞commit9Java:ṹ1.publicfinalvoidcommit(TransactionStatusstatus)throwsTransactionException{2.……3.DefauItTransactionStatusdefStatus=(DefaultTransactionStatus)status;4.if(defStatus.isLocalRollbackOnlyO){5.……6.processRollback(defStatus);7.return;

548.}9.................10.processRollback(defStatus);1112.)13.14.processCommit(defStatus);15.}TransactionstatusḄᐹ]ï᝱Ḅᑨd*ᩭhiᐹ]Ḅᜐᳮ9Java:ṹ1.privatevoidprocessCommit(DefaultTransactionStatusstatus)throwsTransactionException{2.try{3.booleanbeforeCompletionInvoked=false;4.try{5.triggerBeforeCommit(status);6.triggerBeforeCompletion(status);7.beforeCompletionInvoked=true;8.booleanglobalRollbackOnly=false;9.if(status.isNewTransaction()||isFailEarlyOnGlobalRollbackOnly()){10.globalRollbackOnly=status.isGlobalRollbackOnly();11.)12.if(status.hasSavepoint()){13.....................14.status.releaseHeldSavepoint();15.}16.elseif(status.isNewTransaction()){17.……18.doCommit(status);19.}20...................21.)é¡Ḅᵫᐹ]ḄtransactionManagerᩭ*¦᝞ᙠDataSourceTransactionManager:Java:ṹ1.protectedvoiddoCommit(DefaultTransactionStatusstatus){2.஻ᑮᙠTransactionlnf஺ñ@yzḄ3.DataSourceTransactionObjecttxObject=(DataSourceTransactionObject)status.getTransaction();4.5.஻ᑮ¼iḄᦪòó06.Connectioncon=txObject.getConnectionHolder().getConnection();7.............

558.try{9.஻ᦪòó0ᩭÂÃ10.con.commit();11.)1213.)14.15.protectedvoiddoRollback(DefaultTransactionStatusstatus){16.DataSourceTransactionObjecttxObject=(DataSourceTransactionObject)status.getTransaction();17.Connectioncon=txObject.getConnectionHolder().getConnection();18.if(status.isDebugO){19.logger.debugf'RollingbackJDBCtransactiononConnection["+con+"]'*)20.}21.try{22.஻ᦪòó0ᩭIôõ23.con.rollback();24.)25.catch(SQLExceptionex){26.thrownewTransactionSystemException("CouldnotrollbackJDBCtransaction",ex);27.)28.}ᡃG[ᑮᙠDataSourceTransactionManagerᨬ®>ÃconnectionᩭḄÂÃrollback0᦮ÌNᜐᳮ>ᜐᳮᙠSpringAOPḄöᵨ,ᡃG[ᑮvA÷ḄuᵨSpringAOPḄÔÕ*ᙠSpringÌNᜐᳮḄø:ṹᡃG-.[ᑮ91.^᪵îÈᔜû?bëì+Ḅᜐᳮ:ṹ2.^᪵âឋüýᔠᜐᳮ:ṹᩭSᡂþiḄᜐᳮÿᶍ3.᪵ᮣḄᵨSpringAOP᪾஺᝞ᔠ☢ḄSpringAOPḄṹᩭᳮ!"#஺☢ᡃ%ᑖ᪆(SpringAOP)*+,ᑮProxy./Ḅ012☢ᡃ%33ᙠSpringAOP+56ᘤ89᪵:;ᵨḄ<=9Proxy>?9᪵@AᵨḄᡈὅDSpring9᪵Eᡃ%FGAOPHḄIᙠJdkDynamicAopProxy+JᡂProxy./ḄL᎛NJavaṹ1.returnProxy.newProxylnstance(classLoader,proxiedlnterfaces,this);OPḄthisQᦪ.SḄ9InvocationHandler./OPᡃ%ḄJdkDynamicAopProxy)*(OTUV<=9DWProxy./ḄXᦪ:;ᵨḄL᎛OTInvocationHandlerḄinvokeYZ:AE[;Xᦪ;ᵨ2☢ᡃ%33OTYZḄ)*NJavaṹ1.publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{2.Methodinvocationinvocation=null;3.ObjectoldProxy=null;4.booleansetProxyContext=false;

565.6.Targetsourcetargetsource=this.advised.targetSource;7.Classtargetclass=null;8.Objecttarget=null;9.10.try{11.//Tryspecialrulesforequals()methodandimplementationofthe12.//AdvisedAOPconfigurationinterface.13.14.if(Sthis.equalsDefined&&AopUtils.isEqualsMethod(method)){15.//Whatifequalsthrowsexception!?16.//Thisclassimplementstheequals(Object)methoditself.17.returnequals(args[0])?Boolean.TRUE:Boolean.FALSE;18.)19.if(!this.hashCodeDefined&&AopUtils.isHashCodeMethod(method)){20.//ThisclassimplementsthehashCode()methoditself.21.returnnewlnteger(hashCode());22.}23.if(Advised.class==method.getDeclaringClass()){24.//serviceinvocationsonProxyConfigwiththeproxyconfig25.returnAopUtils.invokeJoinpointUsingReflection(this.advised,method,args);26.}27.28.ObjectretVal=null;29.30.if(this.advised.exposeProxy){31.//makeinvocationavailableifnecessary32.oldProxy=AopContext.setCurrentProxy(proxy);33.setProxyContext=true;34.}35.36.//Maybenull.Getaslateaspossibletominimizethetimewe"own"thetarget,37.//incaseitcomesfromapool.38.஻OW9,ᑮ]᪗./ḄᙢYWᯠOT]᪗./ᩭabT)cdᡈe9•TgᓫḄJAVA./39.target=targetSource.getTarget();40.if(target!=null){41.targetclass=target.getClass();42.}43.44.//gettheinterceptionchainforthismethod45.//OPj,klmḄ5nᘤ8

5746.Listchain=this.advised.advisorChainFactory.getlnterceptorsAndDynamicInterceptionAdvice(47.this.advised,proxy,method,targetclass);48.49.//Checkwhetherwehaveanyadvice.Ifwedon't,wecanfallbackondirect50.//reflectiveinvocationofthetarget,andavoidcreatingaMethodinvocation.51.//᝞oᨵqk56ᘤrsᡃ%=tU;ᵨ]᪗Ḅ.SYZ52.if(chain.isEmptyO){53.//WecanskipcreatingaMethodInvocation:justinvokethetargetdirectly54.//NotethatthefinalinvokermustbeanInvokerinterceptorsoweknowitdoes55.//nothingbutareflectiveoperationonthetarget,andnohotswappingorfancyproxying56.retVal=AopUtils.invokeJoinpointUsingReflection(target,method,args);57.)58.else{59.//Weneedtocreateamethodinvocation...60.//invocation=advised.getMethodlnvocationFactory().getMethodlnvocation(61.//proxy,method,targetclass,target,args,chain,advised);62.஻᝞ᨵ56ᘤḄqkrs◤⌕;ᵨ56ᘤwxy;ᵨFl᪗./ḄzSYZ63.//OP{0᪀⌼~TReflectiveMethodlnvocationᩭ)*☢ᡃ%3OTReflectiveMethodlnvocation64.invocation=newReflectiveMethodlnvocation(65.proxy,target,method,args,targetclass,chain);66.67.//proceedtothejoinpointthroughtheinterceptorchain68.//OP{0ReflectiveMethodlnvocationᩭ;ᵨ56ᘤ8zSḄ]᪗YZ69.retVal=invocation.proceed();70.}71.72.//massagereturnvalueifnecessary73.if(retVal!=null&&retVal==target&&method.getReturnType().islnstance(proxy)){74.//Specialcase:itreturned"this"andthereturntypeofthemethodistype-compatible75.//Notethatwecan'thelpifthetargetsets76.//areferencetoitselfinanotherreturnedobject.77.retVal=proxy;78.}79.returnretVal;80.}81.finally{82.if(target!=null&&!targetSource.isStatic()){83.//musthavecomefromTargetsource84.targetSource.releaseTarget(target);85.}86.

5887.if(setProxyContext){88.//restoreoldproxy89.AopContext.setCurrentProxy(oldProxy);90.}91.}92.}ᡃ%ᐜ33]᪗./YZḄ;ᵨOP9{0AopUtilsḄYZ;ᵨ-ᵨᑴᩭ.]᪗./ḄYZ;ᵨNJavaṹ1.publicstaticObjectinvokeJoinpointUsingReflection(Objecttarget,Methodmethod,ObjectQargs)2.throwsThrowable{3.4.//Usereflectiontoinvokethemethod.5.஻ᑭᵨᑴ,ᑮzSḄYZ;ᵨinvoke6.try(7.if(!Modifier.isPublic(method.getModifiers())||8.!Modifier.isPublic(method.getDeclaringClass().getModifiers())){9.method.setAccessible(true);10.}11.returnmethod.invoke(target,args);12.)13.catch(InvocationTargetExceptionex){14.//Invokedmethodthrewacheckedexception.15.//Wemustrethrowit.Theclientwon'tseetheinterceptor.16.throwex.getTargetException();17.)18.catch(HlegalArgumentExceptionex){19.thrownewAoplnvocationException("AOPconfigurationseemstobeinvalid:triedcallingmethod+20.method+"]ontarget[n+target+"]'\ex);21.)22.catch(HlegalAccessExceptionex){23.thrownewAoplnvocationException("Couldn'taccessmethod:"+method,ex);24.)25.}.56ᘤ8Ḅ;ᵨᜐᳮ9ᙠReflectiveMethodlnvocationP)*ḄNJavaṹ1.publicObjectproceed()throwsThrowable{2.//Westartwithanindexof-1andincrementearly.3.஻OPtU;ᵨ]᪗./ḄYZ,oᨵ56ᘤḄ;ᵨᡈὅ56ᘤ;ᵨ(,OTcurrentinterceptorindexḄ90

594.if(this.currentlnterceptorlndex==this.interceptorsAndDynamicMethodMatchers.size()){5.returninvokeJoinpoint();6.}7.8.ObjectinterceptorOrlnterceptionAdvice=9.this.interceptorsAndDynamicMethodMatchers.get(this.currentlnterceptorlndex);10.if(interceptorOrlnterceptionAdviceinstanceofInterceptorAndDynamicMethodMatcher){11.//Evaluatedynamicmethodmatcherhere:staticpartwillalreadyhave12.//beenevaluatedandfoundtomatch.13.஻OPj,zSḄ56ᘤ,᝞56ᘤᓛḄḄr=;ᵨ56ᘤḄinvokeYZ14.InterceptorAndDynamicMethodMatcherdm=15.(InterceptorAndDynamicMethodMatcher)interceptorOrlnterceptionAdvice;16.if(dm.methodMatcher.matches(this.method,this.targetClass,this.arguments)){17.returndm.interceptor.invoke(nextlnvocation());18.}19.else{20.//Dynamicmatchingfailed.21.//Skipthisinterceptorandinvokethenextinthechain.22.஻᝞56ᘤᓛr=;ᵨ2~T56ᘤOTL᎛56ᘤ8Ḅᢣ¡¢£;ᵨWḄproceedYZ23.this.currentlnterceptorlndex++;24.returnproceed();25.}26.}27.else{28.//It'saninterceptor,sowejustinvokeit:Thepointcutwillhave29.//beenevaluatedstaticallybeforethisobjectwasconstructed.30.return((Methodinterceptor)interceptorOrlnterceptionAdvice).invoke(nextlnvocation());31.)32.}OP¤WḄ56ᘤ8¥ᙠ56ᘤ8Ḅ᪗¦§cloneᑮ•TMethodinvocation./(Aᵨ9WḄ56ᘤ᡻wx©ª«Ḽ,ᑮOT56ᘤ8᡻2☢Ḅ56E<=9£Ḅ;ᵨ☢OTproceed:Javaṹ1.privateReflectiveMethodlnvocationnextlnvocation()throwsCloneNotSupportedException{2.ReflectiveMethodlnvocationinvocation=(ReflectiveMethodlnvocation)clone();3.invocation.currentlnterceptorlndex=this.currentlnterceptorlndex+1;4.invocation.parent=this;5.returninvocation;6.}OPḄnextinvocation=ᒹ®(WḄ568Ḅ¯°±²ᡃ%3ᑮᙠInterceptor+Ḅ)*³᝞TransactionInterceptorḄ)*+N

60Javaṹ1.publicObjectinvoke(finalMethodinvocationinvocation)throwsThrowable{2..........//OP9Transactioninterceptor´ᐭḄ¶·ᜐᳮṹᡃ%ᙠ:x¹ᑖ᪆¶·ᜐᳮ)*ḄL᎛ᑖ᪆3.try{4.஻OP9.Ḅ56ᘤ8£ᜐᳮḄ;ᵨ5.retVal=invocation.proceed();6.}7..........஻ḕᶍ(¶·ᜐᳮḄ»¼ᜐᳮṹ<9Transactioninterceptor´ᐭḄᜐᳮ8.else{9.try{10.Objectresult=((CallbackPreferringPlatformTransactionManager)getTransactionManager()).execute(txAttr,11.newTransactionCallback(){12.publicObjectdolnTransaction(TransactionStatusstatus){13.஻OP9Transactioninterceptor´ᐭ.¶·ᜐᳮḄṹ14.Transactioninfotxlnfo=prepareTransactionlnfo(txAttr,joinpointidentification,status);15.஻OP.9.Ḅ56ᘤ8£ᜐᳮḄ;ᵨUḼ½Ḽ56ᘤᜐᳮ16.try{17.returninvocation.proceed();18.}19..........//ḕᶍ('Ji·ᜐᳮḄ»¼ᜐᳮṹ<9Transactioninterceptor´ᐭḄᜐᳮ20.}¾☢Ḅᑖ᪆ᡃ%3ᑮ/SpringAOPḄ¯°)*³᝞Spring᪵,ᑮProxy,᪵ᑭᵨJAVAProxy¥ᑴ.ᵨᡝklḄ56ᘤ8ᜐᳮ஺O/RÀᐹÂ*wxgᓄ(ÄÅÆᩖḄ±²ᢝÉᓄḄÊË஺SpringSᵨÊËὅ{0SpringFGḄO/RYᫀYÍḄᵨᔜÏᢝÉᓄÀᐹ³᝞HibernateN2☢ᡃ%=Spring+Hibemate+ḄSpring)*Ð~TgᓫḄᒈ᪆஺Spring.HinberanateḄ9{0LocalSessionFactoryBeanᩭᡂḄO9~TÀᔆBeanḄ)*ᙠ¯ÓAbstractsessionFactoryBean+NJavaṹ1./**2.*O9FactoryBean◤⌕)*ḄUVYZtUÕ,WḄsessionFactoryḄ3.*/4.publicObjectgetObject(){5.returnthis.sessionFactory;6.}OTᙠafterPropertySet+klNJavaṹ1.publicvoidafterPropertiesSet()throwsException{2.஻OTbuildSessionFactory9{0±²,ᑮSessionFactoryḄᙢY

613.SessionFactoryrawSf=buildSessionFactory();4.஻OPᵨ(ProxyYZ´ᐭ.getCurrentSessionḄ56,ᑮ¶·zᐵḄsession5.this.sessionFactory=wrapSessionFactorylfNecessary(rawSf);6.)ᡃ%ᐜ33SessionFactory9᪵×ØḄOTYZÙÚᒹ®(×ØHibernateḄSessionFactoryḄÛÜÝÞNJavaṹ1.protectedSessionFactorybuildSessionFactory()throwsException{2.SessionFactoryst=null;3.4.//CreateConfigurationinstance.5.Configurationconfig=newConfiguration();6.7.஻OPᦪ߶·àᳮᘤLobHanderᑮHolder»OTHolder9~TThreadLocalâãO᪵O#ä=å1æk(8.if(this.dataSource!=null){9.//MakegivenDataSourceavailableforSessionFactoryconfiguration.10.configTimeDataSourceHolder.set(this.dataSource);11.)12.13.if(this.jtaTransactionManager!=null){14.//MakeSpring-providedJTATransactionManageravailable.15.configTimeTransactionManagerHolder.set(this.jtaTransactionManager);16.}17.18.if(this.lobHandler!=null){19.//MakegivenLobHandleravailableforSessionFactoryconfiguration.20.//Doearlybecausebecausemappingresourcemightrefertocustomtypes.21.configTimeLobHandlerHolder.set(this.lobHandler);22.}23.24.஻OP9ᵨHibernateḄᔜTçឋḄOPᵨConfigurationÓᩭé/O#ᦪß25.try{26.//Setconnectionreleasemode"on_close“asdefault.27.//ThiswasthecaseforHibernate3.0;Hibernate3.1changed28.//itto"auto"(i.e."after_statement"or"afterjransaction").29.//However,forSpring'sresourcemanagement(inparticularfor30.//HibernateTransactionManager),non_close"isthebetterdefault.31.config.setProperty(Environment.RELEASE_CONNECTIONS,ConnectionReleaseMode.ON_CLOSE.toString());32.33.if(HsExposeTransactionAwareSessionFactoryO){34.//NotexposingaSessionFactoryproxywithtransaction-aware

6235.11getCurrentSession()method->setHibernate3.1CurrentSessionContext36.//implementationinstead,providingtheSpring-managedSessionthatway.37.//CanbeoverriddenbyacustomvalueforcorrespondingHibernateproperty.38.config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,39.Morg.springframework.orm.hibernate3.SpringSessionContext");40.}41.42.if(this.entitylnterceptor!=null){43.//SetgivenentityinterceptoratSessionFactorylevel.44.config.setlnterceptor(this.entityinterceptor);45.}46.47.if(this.namingStrategy!=null){48.//PassgivennamingstrategytoHibernateConfiguration.49.config.setNamingStrategy(this.namingStrategy);50.}51.52.if(this.typeDefinitions!=null){53.//RegisterspecifiedHibernatetypedefinitions.54.Mappingsmappings=config.createMappings();55.for(inti=0;i

6378.}79.80.if(this.dataSource!=null){81.booleanactually!ransactionAware=82.(this.useTransactionAwareDataSource||this.dataSourceinstanceofTransactionAwareDataSourceProxy);83.//SetSpring-providedDataSourceasHibernateConnectionProvider.84.config.setProperty(Environment.CONNECTION_PROVIDER,85.actuallyTransactionAware?86.TransactionAwareDataSourceConnectionProvider.class.getName():87.LocalDataSourceConnectionProvider.class.getName());88.}89.90.if(this.jtaTransactionManager!=null){91.//SetSpring-providedJTATransactionManagerasHibernateproperty.92.config.setProperty(93.Environment.TRANSACTION_MANAGER_STRATEGY,LocalTransactionManagerLookup.class.getName());94.}95.96.if(this.mappingLocations!=null){97.//RegistergivenHibernatemappingdefinitions,containedinresourcefiles.98.for(inti=0;i

64120.for(inti=0;i1){138.config.setCacheConcurrencyStrategy(className,strategyAndRegion[0],strategyAndRegion[1]);139.}140.elseif(strategyAndRegion.length>0){141.config.setCacheConcurrencyStrategy(className,strategyAndRegion[0]);142.}143.}144.}145.146.if(this.collectionCacheStrategies!=null){147.//Registercachestrategiesformappedcollections.148.for(EnumerationcollRoles=this.collectionCacheStrategies.propertyNames();collRoles.hasMoreElements();){149.StringcollRole=(String)collRoles.nextElement();150.String[]strategyAndRegion=151.StringUtils.commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));152.if(strategyAndRegion.length>1){153.config.setCollectionCacheConcurrencyStrategy(collRole,strategyAndRegion[0],strategyAndRegion[1]);154.}155.elseif(strategyAndRegion.length>0){156.config.setCollectionCacheConcurrencyStrategy^ollRole,strategyAndRegion[0]);

65157.}158.}159.}160.161.if(this.eventListeners!=null){162.//RegisterspecifiedHibernateeventlisteners.163.for(Iteratorit=this.eventListeners.entrySet().iterator();it.hasNext();){164.Map.Entryentry=(Map.Entry)it.next();165.Assert.isTrue(entry.getKey()instanceofString,"EventlistenerkeyneedstobeoftypeString'1);166.StringlistenerType=(String)entry.getKey();167.Objectlistenerobject=entry.getValue();168.if(listenerobjectinstanceofCollection){169.Collectionlisteners=(Collection)listenerobject;170.EventListenerslistenerRegistry=config.getEventListeners();171.Object[]listenerArray=172.(ObjectQ)Array.newlnstance(listenerRegistry.getListenerClassFor(listenerType),listeners.size());173.listenerArray=listeners.toArray(listenerArray);174.config.setListeners(listenerType,listenerArray);175.}176.else{177.config.setListener(listenerType,listenerobject);178.}179.}180.}181.182.//Performcustompost-processinginsubclasses.183.postProcessConfiguration(config);184.185.//OP9᪷ßConfiguration×ØSessionFactoryḄᙢY186.logger.info("BuildingnewHibernateSessionFactory");187.this.configuration=config;188.sf=newSessionFactory(config);189.}190.஻ᨬx¤å1ækḄäìí191.finally{192.if(this.dataSource!=null){193.//ResetDataSourceholder.194.configTimeDataSourceHolder.set(null);195.}196.197.if(this.jtaTransactionManager•=null){198.//ResetTransactionManagerholder.

66199.configTimeTransactionManagerHolder.set(null);200.}201.202.if(this.lobHandler!=null){203.//ResetLobHandlerholder.204.configTimeLobHandlerHolder.set(null);205.}206.}207.208.//Executeschemaupdateifrequested.209.if(this.schemallpdate){210.updateDatabaseSchema();211.}212.213.returnsf;214.}¹tU;ᵨorg.hibernate.cfg.Configurationᩭ,ᑮ◤⌕ḄSessionFactory:Javaṹ1.protectedSessionFactorynewSessionFactory(Configurationconfig)throwsHibernateException{2.returnconfig.buildSessionFactory();3.)ᡠᡃ%OP3ᑮLocalSessionFactoryᜧð@ᑮḄ~TñÕäᯠxJᡂSessionFactoryḄAᵨIWᯠOPᙠ,ᑮSessionFactorywxò◤⌕.sessionḄ¶·àᳮA~#ᜐᳮ-ᵨ(•TProxy>?.getCurrentSessionYZ(56IJavaṹ1.஻OPᐜ᪷ßWḄSessionFactoryḄÓó,ᑮProxy,ᯠx´ᐭSpringklmḄgetCurrentSession56ᘤ2.protectedSessionFactorygetTransactionAwareSessionFactoryProxy(SessionFactorytarget)(3.Classsflnterface=SessionFactory.class;4.if(targetinstanceofSessionFactorylmplementor){5.sflnterface=SessionFactorylmplementor.class;6.}7.return(SessionFactory)Proxy.newProxylnstance(sflnterface.getClassLoader(),8.newClass[]{sflnterface},newTransactionAwarelnvocationHandler(target));9.}56ᘤḄ)*᝞2NJavaṹ1.privatestaticclassTransactionAwarelnvocationHandlerimplementsInvocationHandler{2.

673.privatefinalSessionFactorytarget;4.5.publicTransactionAwarelnvocationHandler(SessionFactorytarget){6.this.target=target;7.)8.9.publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{10.//InvocationonSessionFactory/SessionFactorylmplementorinterfacecomingin...11.//OP.getCurrentSessionYZ56,ᑮ~TW¶·ækḄsessionôõᵨᡝ12.if(method.getName().equals("getCurrentSession")){13.//HandlegetCurrentSessionmethod:returntransactionalSession,ifany.14.try{15.returnSessionFactorylltils.doGetSession((SessionFactory)proxy,false);16.}17.catch(IHegalStateExceptionex){18.thrownewHibernateException(ex.getMessage());19.}20.}21.elseif(method.getName().equals("equals")){22.//Onlyconsiderequalwhenproxiesareidentical.23.return(proxy==args[0]?Boolean.TRUE:Boolean.FALSE);24.}25.elseif(method.getName().equals("hashCode")){26.//UsehashCodeofSessionFactoryproxy.27.returnnewlnteger(hashCode());28.}29.30.//OP9◤⌕öḄSessionFactoryḄ]᪗YZ31.try{32.returnmethod.invoke(this.target,args);33.}34.catch(InvocationTargetExceptionex){35.throwex.getTargetException();36.}37.}38.}ᡃ%33getCurrentSessionḄ)*ᙠSessionFactoryUtils+NJavaṹ1.privatestaticSessiondoGetSession(2.SessionFactorySessionFactory,Interceptorentityinterceptor,3.SQLExceptionTranslatorjdbcExceptionTranslator,booleanallowCreate)4.throwsHibernateException,IHegalStateException{5.

686.Assert.notNull(sessionFactory,"NoSessionFactoryspecified");78.஻OTTransactionSynchronizationManagerḄResource9——TThreadLocalâft.sessionFactory9~TᓫcøThreadLocal9å1ækḄ9.஻O᪵=)*(Hiberante+¼ᵨḄ{0ThreadLocalḄsessionàᳮᑴ10.SessionHoldersessionHolder=(SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);11.if(sessionHolder!=null&&SsessionHolder.isEmptyO){12.//pre-boundHibernateSession13.Sessionsession=null;14.if(TransactionSynchronizationManager.isSynchronizationActive()&&15.sessionHolder.doesNotHoldNonDefaultSession()){16.//Springtransactionmanagementisactive->17.//registerpre-boundSessionwithitfortransactionalflushing.18.session=sessionHolder.getValidatedSession();19.if(session!=null&&!sessionHolder.isSynchronizedWithTransaction()){20.logger.debug(HRegisteringSpringtransactionsynchronizationforexistingHibernateSession");21.TransactionSynchronizationManager.registerSynchronization(22.newSpringSessionSynchronization(sessionHolder,sessionFactory,jdbcExceptionTranslator,false));23.sessionHolder.setSynchronizedWithTransaction(true);24.//SwitchtoFlushMode.AUTO,aswehavetoassumeathread-boundSession25.//withFlushMode.NEVER,whichneedstoallowflushingwithinthetransaction.26.FlushModeflushMode=session.getFlushMode();27.if(flushMode.lessThan(FlushMode.COMMIT)&&28.•TransactionSynchronizationManager.isCurrentTransactionReadOnlyO){29.session.setFlushMode(FlushMode.AUTO);30.sessionHolder.setPreviousFlushMode(flushMode);31.)32.}33.)34.else{35.//NoSpringtransactionmanagementactive->tryJTAtransactionsynchronization.36.session=getJtaSynchronizedSession(sessionHolder,sessionFactory,jdbcExceptionTranslator);37.)38.if(session!=null){39.returnsession;40.)41.)42.//OPtUᡭÊ~TSession43.logger.debugfOpeningHibernateSession");44.Sessionsession=(entityinterceptor!=null?

6945.sessionFactory.openSession(entitylnterceptor):sessionFactory.openSession());46.47.//UsesameSessionforfurtherHibernateactionswithinthetransaction.48.//Threadobjectwillgetremovedbysynchronizationattransactioncompletion.49.//¤üᡭÊḄSessionýijSessionHolder,ᯠxᑮThreadLocalP☢þå1æk@ᩭOTThreadLocal9ᙠTransactionSynchronizationManager•+mḄ᪷ßsessionFactoryᩭÿ50.I᪷ᜐᳮḄ᝱ᩭsessionḄឋ᝞FlushModeNever,sessionᜐᳮᐵὶᩭ51.if(TransactionSynchronizationManager.isSynchronizationActiveO){52.//We'rewithinaSpring-managedtransaction,possiblyfromJtaTransactionManager.53.logger.debug("RegisteringSpringtransactionsynchronizationfornewHibernateSessionH)54.SessionHolderholderToUse=sessionHolder;55.if(holderToUse==null){56.holderToUse=newSessionHolder(session);57.}58.else{59.holderTollse.addSession(session);60.}61.if(TransactionSynchronizationManager.isCurrentTransactionReadOnlyO){62.session.setFlushMode(FlushMode.NEVER);63.}64.TransactionSynchronizationManager.registerSynchronization(65.newSpnngSessionSynchronization(holderToUse,sessionFactory,jdbcExceptionTranslator,true));66.holderTollse.setSynchronizedWithTransaction(true);67.if(holderToUse!=sessionHolder){68.TransactionSynchronizationManager.bindResource(sessionFactory,holderToUse);69.}70.}71.else{72.//NoSpringtransactionmanagementactive->tryJTAtransactionsynchronization.73.registerJtaSynchronization(session,sessionFactory,jdbcExceptionTranslator,sessionHolder);74.)75.76.//CheckwhetherweareallowedtoreturntheSession.77.if(lallowCreate&&!isSessionTransactional(session,sessionFactory)){78.closeSession(session);79.thrownewHlegalStateException("NoHibernateSessionboundtothread,M+80."andconfigurationdoesnotallowcreationofnon-transactionalonehere'*)81.)

7082.83.returnsession;84.}!ᙠSpring#$ᵨHiberanteḄSessionFactory&'Session(Ḅ)ᜓ+,ᙠ-.Ạ0ᵨᡝ2&34$ᵨHibernateTemplateᩭ$ᵨHibernateḄO/R56,&89ᑮḄ;᪵!;-executeḄ=>?Java@ṹ1.publicObjectexecute(HibernateCallbackaction,booleanexposeNativeSession)throwsDataAccessException{2.Assert.notNull(action,"Callbackobjectmustnotbenull");3.஻CᑮDḄHibernateḄSession4.Sessionsession=getSession();5.booleanexistingTransaction=SessionFactoryUtils.isSessionTransactional(session,getSessionFactoryO);6.if(existingTransaction){7.logger.debug(HFoundthread-boundSessionforHibernateTemplate");8.)9.10.FlushModepreviousFlushMode=null;11.try{12.previousFlushMode=applyFlushMode(session,existingTransaction);13.enableFilters(session);14.SessionsessionToExpose=(exposeNativeSession?session:createSessionProxy(session));15.஻!=>ḄᐭF16.Objectresult=action.dolnHibernate(sessionToExpose);17.flushlfNecessary(session,existing?ransaction);18.returnresult;19.}20.catch(HibernateExceptionex){21.throwconvertHibernateAccessException(ex);22.}23.catch(SQLExceptionex){24.throwconvertJdbcAccessException(ex);25.}26.catch(RuntimeExceptionex){27.//Callbackcodethrewapplicationexception...28.throwex;29.}30.finally{31.஻᝞G->ᵨḄHIᙠ;-J#32.if(existingTransaction){33.logger.debug("Notclosingpre-boundHibernateSessionafterHibernateTemplate");

7134.disableFilters(session);35.if(previousFlushMode!=null){36.session.setFlushMode(previousFlushMode);37.}38.}஻ᔲᑣSessionᐵN39.else{40.//NeverusedeferredcloseforanexplicitlynewSession.41.if(isAlwaysllseNewSession()){42.SessionFactoryUtils.closeSession(session);43.}44.else{45.SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session,getSessionFactory());46.}47.)48.}49.}ᡃP99Q᪵CᑮRSḄSessionḄTᯠ$ᵨVSessionFactoryUtilsḄHIdoGetSession:Java@ṹ1.protectedSessiongetSession(){2.if(isAlwaysUseNewSession()){3.returnSessionFactoryUtils.getNewSession(getSessionFactory(),getEntitylnterceptor());4.)5.elseif(HsAllowCreate()){6.returnSessionFactorylltils.getSession(getSessionFactory(),false);7.}8.else{9.returnSessionFactoryUtils.getSession(10.getSessionFactory(),getEntitylnterceptor(),getJdbcExceptionTranslator());11.)12.)Wᓫᑖ᪆[SpringAcegiḄ\@ṹ]^?Servlet.AlterḄ]^AuthenticationProcessingFilter_`Web⚓☢Ḅcd4e;ᙠAbstractProcessingHIterfgV᦮-cd4eḄij?Java@ṹ1.publicvoiddoFlter(ServletRequestrequest,ServletResponseresponse,FlterChainchain)2.throwslOException,ServletException{3.஻kc!l!mᔠServletRequest/SevletResponseḄ⌕p4.if('(requestinstanceofHttpServletRequest)){5.thrownewServletException("CanonlyprocessHttpServletRequest");

726)7.8.if('(responseinstanceofHttpServletFtesponse)){9.thrownewServletException("CanonlyprocessHttpServletResponse");10.}11.12.HttpServletRequesthttpRequest=(HttpServletRequest)request;13.HttpServletResponsehttpResponse=(HttpServletResponse)response;14.//᪷HttpServletRequestHttpServletResponseᩭrscd15.if(requiresAuthentication(httpRequest,httpResponse)){16.if(logger.isDebugEnabled()){17.Iogger.debug("Requestistoprocessauthentication");18.}19.஻fgAcegi#ḄAuthenticationRtᩭᢝᨵwᐵḄᵨᡝcdxy20.AuthenticationauthResult;21.22.try(23.onPreAuthentication(httpRequest,httpFtesponse);24.஻Ḅᐹ{cd4e|ᡲ~ᡂ᝞AuthenticationProcessingFilterᩭᡂ.Web☢Ḅᵨᡝcd25.authResult=attemptAuthentication(httpRequest);26.}catch(AuthenticationExceptionfailed){27.//Authenticationfailed28.unsuccessfulAuthentication(httpRequest,httpResponse,failed);29.30.return;31.)32.33.//Authenticationsuccess34.if(continueChainBeforeSuccessfulAuthentication){35.chain.doFlter(request,response);36.}37.஻ᡂcdḄ+,᝞ᑮwSḄ⚓☢38.sucx:essfulAuthentication(httpRequest,httpResponse,authResult);39.40.return;41.)42.43.chain.doFilter(request,response);44.}ᙠAuthenticationProcessingFilter#Ḅᐹ{cd4e!᪵Ḅ?Java@ṹ

731.publicAuthenticationattemptAuthentication(HttpServletRequestrequest)2.throwsAuthenticationException{3.஻HttpServletRequest#CᑮᵨᡝcdḄᵨᡝṹ4.Stringusername=obtainllsername(request);5.Stringpassword=obtainPassword(request);6.7.if(username==null){8.username=,,M;9.)10.11.if(password==null){12.password=M";13.)14.஻᪷CᑮḄᵨᡝṹ᪀⌼;-AuthenticationRt~AuthenticationManagerrscd☢ᒹVᵨᡝḄᵨᡝṹxy15.UsernamePasswordAuthenticationTokenauthRequest=newUsernamePasswordAuthenticationToken(username,password);16.17.//PlacethelastusernameattemptedintoHttpSessionforviews18.request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,username);19.20.//Allowsubclassestosetthe"details"property21.setDetails(request,authRequest);22.஻_`AuthenticationManagerrscd4e23.returnthis.getAuthenticationManager().authenticate(authRequest);24.}ᙠAcegi᪾#rscdᳮḄ⌕!AuthenticationManager,ᡃP99!Q᪵rscdᳮḄ-cdḄ>ᵨᐭF!authenticateᙠAbstractAuthenticationManager?஻!rscdḄᦪ=•-AuthenticationRtᩭcdḄGᐸ#ᒹVᵨᡝḄcdxyᩗ▲£-Authentication¤&¥ᣴᩗiᙽ$ᵨJava@ṹ1.஻᝞Gcdᜫ©ª«ᙠcd4e#¤¬®¯°±2.publicfinalAuthenticationauthenticate(AuthenticationauthRequest)3.throwsAuthenticationException{4.try{஻!]▭ḄcdᜐᳮᡃP[☢$ᵨProviderManagerᩭ´µᐹ{Ḅcd4e¶ᐭḄ·ᦪauthRequest☢¸¹ᒹVHttpServletRequest#CᑮḄᵨᡝºᐭḄᵨᡝṹ5.AuthenticationauthResult=doAuthentication(authRequest);6.copyDetaiIs(authFtequest,authResult);7.8.returnauthResult;9.}catch(AuthenticationExceptione){10.e.setAuthentication(authRequest);

7411.throwe;12.)13.}ᙠRoviderManager#rs]▭Ḅcd+,Ꮇ$ᵨᦪ¼ᩭ½ᵨᡝxy?Java@ṹ1.publicAuthenticationdoAuthentication(Authenticationauthentication)2.throwsAuthenticationException{3.஻CDḄprovider¾Ḅ¿@ᘤᙠḄ᎛2&Â-provider,ᡃPḄ!DaoAuthenticationProviderᩭ´µ$ᵨᦪ¼ᩭýᵨᡝḄᵨᡝṹxy஺4.Iteratoriter=providers.iterator();5.6.QasstoTest=authentication.getQass();7.8.AuthenticationExceptionlastException=null;9.10.while(iter.hasNext()){11.Authenticationproviderprovider=(Authenticationprovider)iter.next();12.13.if(provider.supports(toTest)){14.Iogger.debug("Authenticationattemptusing"+provider.get0ass().getName());15.஻-resultᒹVcd#CᑮḄGxy16.Authenticationresult=null;17.18.try{஻!providerrscdᜐᳮḄ4e19.result=provider.authenticate(authentication);20.sessionController.checkAuthenticationAllowed(result);21.}catch(AuthenticationExceptionae){22.lastException=ae;23.result=null;24.)25.26.if(result!=null){27.sessionController.registerSuccessfulAuthentication(result);28.publishB/ent(newAuthenticationSuccessEvent(result));29.30.returnresult;31.)32.}33.)34.35.if(lastException==null){

7536.lastException=newProviderNotFbundException(messages.getMessage(',ProviderManager.providerNotFbund",37.newObject[]{toTest.getName()},"NoAuthenticationproviderfoundfor{0}”))38.}39.40.//ÅÆÇᩭ3È0[ᦻḄÊËᘤ41.StringclassName=exceptionMappings.getProperty(lastException.getaass().getName());42.AbstractAuthenticationEventevent=null;43.44.if(className!=null){45.try{46.Classclazz=getQass().getaassLoader().loadaass(className);47.Constructorconstructor=clazz.getConstructor(newClassF{48.Authentication.class,AuthenticationException.class49.})50.Objectobj=constructor.newlnstance(newObject[]{authentication,lastException})51.Assert.islnstanceOf(AbstractAuthenticationEvent.class,obj,"MustbeanAbstractAuthenticationEventH)52.event=(AbstractAuthenticationEvent)obj;53.}catch(QassNotFoundExceptionignored){}54.catch(NoSuchMethodExceptionignored){}55.catch(IHegalAccessExceptionignored){}56.catch(InstantiationExceptionignored){}57.catch(InvocationTargetExceptionignored){}58.}59.60.if(event!=null){61.publishEvent(event);62.}else{63.if(logger.isDebugEnabled()){64.logger.debug("Noeventwasfoundfortheexception"+lastException.getaass().getName());65.}66.}67.68.//Throwtheexception69.throwlastException;70.}ᡃP[☢99ᙠDaoAuthenticationProvider!Q᪵ᦪ¼#¯RSḄcdxyrsᵨᡝcdḄᙠḄ.AbstractUserDetailsAuthenticationProviderfgVcdḄᜐᳮij?

76Java@ṹ1.publicAuthenticationauthenticate(Authenticationauthentication)2.throwsAuthenticationException{3.Assert.islnstanceOf(UsernamePasswordAuthenticationToken.class,authentication,4.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",5."OnlyUsernamePasswordAuthenticationTokenissupported'1));6.7.//CᵨᡝºᐭḄᵨᡝ8.Stringusername=(authentication.getPrincipal()==null)?"NONE_PROVIDED":authentication.getName();9.஻᝞GV̽̽#&8½ᐭḄᵨᡝcdxy-!UserDetail,!Íᘤνᙠᦪ¼Ḅᵨᡝxy᪵lᵨÏÐÑᦪ¼#V10.booleancacheWasUsed=true;11.UserDetailsuser=this.userCache.getUserFromCache(username);12.஻Òᨵᑮ᪗ÔÕ[☢¤ÐᑮḄÍᘤÎᵨᡝxy½ᐭ̽#13.if(user==null){14.cacheWasUsed=false;15.16.try{஻!>ᵨUserDetailServiceᵨᡝᦪ¼xyḄᙢH17.user=retrieveUser(username,(UsernamePasswordAuthenticationToken)authentication)18.}catch(UsernameNotFoundExceptionnotFound){19.if(hideUserNotFbundExceptions){20.thrownewBadCredentialsException(messages.getMessage(21."AbstractUserDetailsAuthenticationProvider.badCredentials,,HBadcredentialsJ”))22.}else{23.thrownotFbund;24)25.}26.27.Assert.notNull(user,''retrievellserreturnednull-aviolationoftheinterfacecontract");28.}29.30.if(!user.isAccountNonLocked()){31.thrownewLockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked”,32."Useraccountislocked"));33.)34.35.if(laser.isEnabled()){36.thrownewDisabledException(messages.getMessage(nAbstractllserDetailsAuthenticationProvider.disabled",37."Userisdisabled"));

7738.}39.40.if(!user.isAccountNonExpired()){41.thrownewAccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",42."Useraccounthasexpired"));43.)44.45.//Thischeckmustcomehere,aswedon'twanttotellusers46.//aboutaccountstatusunlesstheypresentedthecorrectcredentials47.try{஻!cd4eᙠretrieveUser#ᦪ¼#CᑮᵨᡝḄxy,3additionalAuthenticationChecks#rsRᵨᡝºᐭÍᘤÎḄᵨᡝxy48.஻᝞Gcd34ª«᪀⌼•-AuthenticationRtᩭÙ&Ḅᣴᩗ$ᵨ᝞Gcdl34¬®¯°±Ú␺ᩗ4e49.additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken)authentication);50.}catch(AuthenticationExceptionexception){51.if(cacheWaslIsed){52.//Therewasaproblem,sotryagainafterchecking53.//we'reusinglatestdata(ienotfromthecache)54.cacheWaslIsed=false;55.user=retrieveUser(username,(UsernamePasswordAuthenticationToken)authentication)56.additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken)authentication);57.}else{58.throwexception;59)60.}61.62.if(laser.isCredentialsNonExpired()){63.thrownewCredentialsExpiredException(messages.getMessage(64."AbstractUserDetailsAuthenticationProvider.credentialsExpired","Usercredentialshaveexpired"));65.}66.஻᪷8☢Ḅ̽GÜf!l!⌕J8Ḅᵨᡝxy½ᐭ̽&[Ðcd$ᵨ67.if(!cacheWaslIsed){68.this.userCache.putUserlnCache(user);69.}70.71.ObjectprincipalToReturn=user;72.73.if(forcePrincipalAsString){74.principalToReturn=user.getUsername();

7875.)76.஻ᨬ=AuthenticationVcdG&Ḅᣴᩗ$ᵨ77.returncreateSuccessAuthentication(principalToReturn,authentication,user);78.}79.஻!!>ᵨUserDetailServiceßàÍᘤÎᵨᡝxyḄᙢHá«ᙢHßà⌕9ᡃPᎷᵫJdbcDaoImpᩭᦪ#rsßà80.protectedfinalUserDetailsretrievellser(Stringusername,UsernamePasswordAuthenticationTokenauthentication)81.throwsAuthenticationException{82.UserDetailsloadedUser;83.஻>ᵨUserDetailServiceᦪ¼#ßᡃᵨᡝcdxy=ᦪ¼#=ḄxyãxyäᑮVUserDetailsRt#V84.try{85.loadedllser=this.getllserDetailsService().loadUserByllsername(username);86.}catch(DataAccessExceptionrepositoryProblem){87.thrownewAuthenticationServiceException(repositoryProblem.getMessage(),repositoryProblem);88.}89.90.if(loadedllser==null){91.thrownewAuthenticationserviceException(92."UserDetailsServicereturnednull,whichisaninterfacecontractviolation**)93)94.returnloadedllser;95.}[☢ᡃPåæᑖ᪆;[JdbcDaoImp-ᩭ99ᐹ{!Q᪵ᦪ¼#CᑮᵨᡝxyḄ?Java@ṹ1.publicclassJdbcDaoImpIextendsJdbcDaoSupportimplementsUserDetailsService{2.஻~Staticfields/initializers=======================================3.஻!⚜fgDḄRèéêëRSìíḄᦪ¼⊤᪀ï2&ðñfgèéêëRSᱯfḄᵨᡝᦪ¼cd⊤Ḅó4.publicstaticfinalStringDEFLUSER^B\LUSERNAME_QUERY=5."SELKTusername,password,enabledFTOMusersWHEREusername=6.publicstaticfinalStringDEF_AUTHORITIE^B\LU8ERNAM^QUERY=7."SELECTusername,authorityFROMauthoritiesWHEREusername=8.9.஻~Instancefields============================================10.஻$ᵨSpringJDBCᩭrsᦪ¼ô,11.protectedMappingSqlQueryauthoritiesByllsernameMapping;12.protectedMappingSqlQueryusersByllsernameMapping;

7913.privateStringauthoritiesByUsernameQuery;14.privateStringrolePrefix=HM;15.privateStringusersByUsernameQuery;16.privatebooleanusernameBasedPrimaryKey=true;17.18.஻~Constructors=============================================19.஻ᙠõöᓄᦪ#èéêë⚜fgḄSQLêë20.publicJdbcDaolmpl(){21.usersByUsernameQuery=DEFLUSERSLBXCUSERNAME_QUERY;22.authoritiesByUsernameQuery=DEF_AUTHORITlES_B\LUSERNAME_QUERY;23.)24.25.஻~Methods================================================26.27.protectedvoidaddCustomAuthorities(Stringusername,Listauthorities){}28.29.publicStringgetAuthoritiesByUsernameQuery(){30.returnauthoritiesByUsernameQuery;31.)32.33.publicStringgetRolePrefix(){34.returnrolePrefix;35.)36.37.publicStringgetUsersByUsernameQuery(){38.returnusersByUsernameQuery;39.)40.41.protectedvoidinitDao()throwsApplicationcontextException{42.initMappingSqlCXjeries();43.}44.45./**46.*ExtensionpointtoallowotherMappingSqlQueryobjectstobesubstitutedinasubclass47.*/48.protectedvoidinitMappingSqlQueries(){49.this.usersByUsernameMapping=newUsersByUsernameMapping(getDataSource());50.this.authoritiesByllsernameMapping=newAuthoritiesByUsernameMapping(getDataSource());51.)52.53.publicbooleanisllsernameBasedPrimaryKey(){

8054.returnusernameBasedPrimaryKey;55.}56.஻!Cᦪ¼ᵨᡝxyḄᐹ{4e57.publicUserDetailsloadUserByllsername(Stringusername)58.throwsUsernameNotFbundException,DataAccessException{59.஻᪷ᵨᡝᙠᵨᡝ⊤UøCᑮᵨᡝxyᒹùᵨᡝṹᵨᡝ!ᔲᨵᦔḄxy60.Listusers=usersByUsernameMapping.execute(username);61.62.if(users.size()==0){63.thrownewUsernameNotF6undException("Usernotfound");64.}65.஻ûᔠ#Ḅü;-,ᨵᦔḄᵨᡝRt66.UserDetailsuser=(UserDetails)users.get(O);//containsnoGrantedAuthority!]67.஻ᙠᩗ▲⊤#CᵨᡝḄᩗ▲xy᪵Ḅ=;-ᩗ▲ûᔠRS-ᵨᡝ68.ListdbAuths=authoritiesByUsernameMapping.execute(user.getllsername());69.70.addCustomAuthorities(user.getUsername(),dbAuths);71.72.if(dbAuths.size()==0){73.thrownewUsernameNotFoundException("UserhasnoGrantedAuthority");74.)75.஻᪷CᑮḄᩗ▲ûᔠᩭ=ḄUserRt&$ᵨ76.GrantedAuthority!]arrayAuths=(GrantedAuthority[])dbAuths.toArray(newGrantedAuthority[dbAuths.size()]);77.78.Stringreturnllsername=user.getUsername();79.80.if(JusernameBasedPrimaryKey){81.returnUsername=username;82.}83.84.returnnewUser(returnUsername,user.getPassword(),user.isEnabled(),true,true,true,arrayAuths);85.}86.87.publicvoidsetAuthoritiesByllsernameQuery(Stringquerystring){88.authoritiesByllsernameQuery=queryString;89.}90.91.publicvoidsetFk)lePrefix(StringrolePrefix){92.this.rolePrefix=rolePrefix;93}94.95.publicvoidsetUsernameBasedPrimaryKey(booleanusernameBasedPrimaryKey){

8196.this.usernameBasedPrimaryKey=usernameBasedPrimaryKey;97.)98.99.publicvoidsetUsersByllsernameQuery(StringusersByllsernameQueryString){100.this.usersByllsernameQuery=usersByllsernameQueryString;101.}102.103.஻~InnerQasses============================================104.105.1**106.*!>ᵨSpringJDBCḄᦪ¼ô,ᐹ{2&·ὃRJDBCḄᑖ᪆-Ḅ,ᵨ!ᦪ¼èéCᑮḄûᔠᣚᔠ-•ᓫḄ0/R107.*/108.protectedclassAuthoritiesByllsernameMappingextendsMappingSqlQuery{109.protectedAuthoritiesByUsernameMapping(DataSourceds){110.super(ds,authoritiesByUsernameQuery);111.declareParameter(newSqlParameter(Types.VARCHAR));112.compile();113.)114.115.protectedObjectmapRow(ResultSetrs,intrownum)116.throwsSQLException{117.StringroleName=rolePrefix+rs.getString(2);118.GrantedAuthoritylmplauthority=newGrantedAuthoritylmpl(roleName);119.120.returnauthority;121.)122.}123.124./**125.*Queryobjecttolookupauser.126.*/127.protectedclassUsersByllsernameMappingextendsMappingSqlQuery{128.protectedUsersByllsernameMapping(DataSourceds){129.super(ds,usersByllsernameQuery);130.declareParameter(newSqlParameter(Types.VARCHAR));131.compile();132.)133.134.protectedObjectmapRow(ResultSetrs,intrownum)135.throwsSQLException{136.Stringusername=rs.getString(l);137.Stringpassword=rs.getString(2);

82138.booleanenabled=rs.getBoolean(3);139.UserDetailsuser=newUser(username,password,enabled,true,true,true,140.newGrantedAuthority[]{newGrantedAuthoritylmpl(HHOLDER")});141.142.returnuser;143.}144.}145.}ᦪᑮᵨᡝ•ᵨᡝ!ᐭḄ#$ᦪᵨᡝḄ%&$%&ᙠDaoAuthenticationProvider:Java(ṹ1.஻$UserDetailᦪ᩵,ᑮḄ$authenticationᵨᡝ!ᐭᑮḄ2.protectedvoidadditionalAuthenticationChecks(UserDetailsuserDetails,3.UsernamePasswordAuthenticationTokenauthentication)4.throwsAuthenticationException{5.Objectsalt=null;6.7.if(this.saltSource!=null){8.salt=this.saltSource.getSalt(userDetails);9.}10.஻᝞.ᵨᡝ/ᨵ!ᐭ1ṹ23456711.if(authentication.getCredentials()==null){12.thrownewBadCredentialsException(messages.getMessage(13."AbstractUserDetailsAuthenticationProvider.badCredentials","Badcredentials"),14.includeDetailsObject?UserDetails:null);15.)16.஻$89ᵨᡝ!ᐭḄ1ṹ17.StringpresentedPassword=authentication.getCredentials()==null?"":authentication.getCredentials().toString();18.஻$8ᑨ;ᵨᡝ!ᐭḄ1ṹ<#ᦪ8Ḅ1ṹ=>$8?@Aᵨpassword&icoderᩭᦪ8Ḅ1ṹCD119.//᝞.<=>4567᝞.=>ᑣ␺ᩗᡂI20.if(!passwordEncoder.isPasswordValid(21.userDetails.getPassword(),presentedPassword,salt)){22.thrownewBadCredentialsException(messages.getMessage(23."AbstractUserDetailsAuthenticationProvider.badCredentials","Badcredentials"),24.includeDetailsObject?UserDetails:null);25.)26.)J☢ᑖ᪆N᦮AcegiPQRSḄ%&AuthenticationProcessingFilterTUHttpVWᑮᵨᡝ!ᐭḄᵨᡝX#1ṹ$Yᵨᡝ!ᐭḄRSZ[\ᑮAuthenticationᢝᨵ^_⌴a

83AuthenticatioManagerᩭᙠbcdḄᵨᡝᩭeᡂ᦮␺ᩗ஺$␺ᩗeᡂ@ZgᨵᦔḄᵨᡝ\ᙠiAuthenticationj@ḄᣴᩗlᙽAᵨ஺ᙠᐹoḄ␺ᩗ%&AᵨNᡃqrstḄᔜvProvider@wxḄUserDetailService#Encoderyᩭeᡂ=xḄz9bcᘤdᵨᡝᦪ@w|ᵨᡝ!ᐭḄRSḄ}~஺ᡃqFilterSecuritylnterceptorᡃqᐭ᪵PQᣴᩗḄJava(ṹ1.஻$8TUᘤTUHTTPVWḄᐭ2.publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)3.throwslOException,ServletException{4.Filterinvocationfi=newFilterlnvocation(request,response,chain);5.invoke(fi);6.)7.஻$ᐹoḄTUᵨ8.publicvoidinvoke(Filterlnvocationfi)throwslOException,ServletException{9.if((fi.getRequest()!=null)&&(fi.getRequest().getAttribute(FILTER_APPLIED)!=null)10.&&observeOncePerRequest){11.஻ᙠiPQ%ᐰg᪗tFILTER_APPLIED,ᨵVWḄᐰN15.if(fi.getRequest()null){16.fi.getRequest().setAttribute(FILTER_APPLIED,Boolean.TRUE);17.)18.஻$8ᐰḄᙢ19.1nterceptorStatusTokentoken=super.beforelnvocation(fi);20.஻3ḼᔣTUᘤ᡻Q21.try{22.fi.getChain().doFilter(fi.getRequest(),fi.getResponse());23.}finally{24.super.afterlnvocation(token,null);25.}26.)27.)Java(ṹ1.஻$8TUᘤTUHTTPVWḄᐭ2.publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)3.throwslOException,ServletException{4.Filterinvocationfi=newFilterlnvocation(request,response,chain);5.invoke(fi);6}7.஻$ᐹoḄTUᵨ

848.publicvoidinvoke(Filterlnvocationfi)throwslOException,ServletException{9.if((fi.getRequest()!=null)&&(fi.getRequest().getAttribute(FILTER_APPLIED)!=null)10.&&observeOncePerRequest){11.஻ᙠiPQ%ᐰg᪗t-FILTER_APPLIED,ᨵVWḄᐰN15.if(fi.getRequest()!=null){16.fi.getRequest().setAttribute(FILTER_APPLIED,Boolean.TRUE);17.)18.஻$8ᐰḄᙢ19.InterceptorStatusTokentoken=super.beforelnvocation(fi);20.஻3ḼᔣTUᘤ᡻Q21.try(22.fi.getChain().doFilter(fi.getRequest(),fi.getResponse());23.}finally{24.super.afterlnvocation(token,null);25.)26.)27.)ᡃqᙠAbstractsecurityinterceptor᪵HTTPVW~ᐰḄJava(ṹ1.protectedInterceptorStatusTokenbeforelnvocation(Objectobject){2.Assert.notNull(object,"Objectwasnull");3.4.if(!getSecureObjectClass().isAssignableFrom(object.getClass())){5.thrownewHlegalArgumentException("Securityinvocationattemptedforobject"6.+object.getClass().getName()7.+"butAbstractsecurityinterceptoronlyconfiguredtosupportsecureobjectsoftype:"8.+getSecureObjectClass());9.}10.஻$89rFilterSecuritylnterceptorḄObjectDefinitionSource¡ឋ$Y¡ឋrN£¤Ḅᐰ11.ConfigAttributeDefinitionattr=this.obtainObjectDefinitionSource().getAttributes(object);12.13.if(attr==null){14.if(rejectPubliclnvocations){15.thrownewHlegalArgumentException(16."NopublicinvocationsareallowedviathisAbstractsecurityinterceptor.M17.+"Thisindicatesaconfigurationerrorbecausethe"18.+"AbstractSecuritylnterceptor.rejectPublicInvocationspropertyissetto'true'");19.}

8520.21.if(logger.isDebugEnabled()){22.logger.debug("Publicobject-authenticationnotattempted");23.)24.25.publishEvent(newPubliclnvocationEvent(object));26.27.returnnull;//nofurtherworkpost-invocation28.}29.30.31.if(logger.isDebugEnabled()){32.logger.debug("Secureobject:"+object.toString()+ConfigAttributes:"+attr.toStringO);33.)34.஻$8SecurityContextHolder¥9Authenticationi¦ᙠ§¨Z\ᑮSecurityContextHolder¥35.if(SecurityContextHolder.getContext().getAuthentication()==null){36.credentialsNotFound(messages.getMessage("AbstractSecuritylnterceptor.authenticationNotFound",37."AnAuthenticationobjectwasnotfoundintheSecurityContext"),object,attr);38.}39.40.஻᝞.©☢/ᨵᜐᳮ␺ᩗ$8◤⌕␺ᩗPQᜐᳮ41.Authenticationauthenticated;42.43.if(!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()||alwaysReauthenticate){44.try{஻ᵨrtḄAuthenticationManagerᜐᳮ␺ᩗ᝞.␺ᩗ<ᡂI4567®ᜐᳮ45.authenticated=this.authenticationManager.authenticate(SecurityContextHolder.getContext()46..getAuthentication());47.}catch(AuthenticationExceptionauthenticationException){48.throwauthenticationException;49.}50.51.//Wedon'tauthenticated.setAuthentication(true),becauseeachprovidershoulddothat52.if(logger.isDebugEnabled()){53.logger.debug("SuccessfullyAuthenticated:"+authenticated.toStringO);54.)55.஻$8g␺ᩗᡂIᑮḄAuthentication¯°ᑮSecurityContextHolderj±Aᵨ56.SecurityContextHolder.getContext().setAuthentication(authenticated);57.}else{஻$8ᜐᳮ©☢²³´%␺ᩗḄVWᐜSecurityContextHolder¥9Authentication

8658.authenticated=SecurityContextHolder.getContext().getAuthentication();59.60.if(logger.isDebugEnabled()){61.logger.debug("PreviouslyAuthenticated:"+authenticated.toString());62.)63.)64.65.஻$ᜐᳮᣴᩗḄ%&66.try{67.஻ᵨrtḄAccessDecisionManagerᩭPQᣴᩗ68.this.accessDecisionManager.decide(authenticated,object,attr);69.}catch(AccessDeniedExceptionaccessDeniedException){70.஻ᣴᩗ<ᡂIᔣ᜜·¸¹º71.AuthorizationFailureEventevent=newAuthorizationFailureEvent(object,attr,authenticated,72.accessDeniedException);73.publishEvent(event);74.75.throwaccessDeniedException;76.)77.78.if(logger.isDebugEnabled()){79.logger.debug("Authorizationsuccessful");80.)81.82.AuthorizedEventevent=newAuthorizedEvent(object,attr,authenticated);83.publishEvent(event);84.85.//$8᪀¼iRunAsManagerᩭ½(¾©ḄAuthentication¿ÀÁ±.AᵨḄNullRunAsManagerZgSecuiityContextHolderÄḄAuthenticationÅÆ86.AuthenticationrunAs=this.runAsManager.buildRunAs(authenticated,object,attr);87.88.if(runAs==null){89.if(logger.isDebugEnabled()){90.logger.debug("RunAsManagerdidnotchangeAuthenticationobject")Ç91.)92.93.//nofurtherworkpost-invocation94.returnnewlnterceptorStatusToken(authenticated,false,attr,object);95.}else{96.if(logger.isDebugEnabled()){97.logger.debug("SwitchingtoRunAsAuthentication:"+runAs.toStringO);98.)99.

87100.SecurityContextHolder.getContext().setAuthentication(runAs);101.102,//reverttotoken.Authenticatedpost-invocation103.returnnewlnterceptorStatusToken(authenticated,true,attr,object);104.)105.}Java(ṹ1.protectedInterceptorStatusTokenbeforelnvocation(Objectobject){2.Assert.notNull(object,"Objectwasnull");3.4.if(!getSecureObjectClass().isAssignableFrom(object.getClass())){5.thrownewHlegalArgumentException("Securityinvocationattemptedforobject"6.+object.getClass().getName()7.+"butAbstractsecurityinterceptoronlyconfiguredtosupportsecureobjectsoftype:“8.+getSecureObjectClass());9.)10.஻$89rFilterSecuritylnterceptorḄObjectDefinitionSource¡ឋ$Y¡ឋrN£¤Ḅᐰ11.ConfigAttributeDefinitionattr=this.obtainObjectDefinitionSource().getAttributes(object);12.13.if(attr==null){14.if(rejectPubliclnvocations){15.thrownewHlegalArgumentException(16."NopublicinvocationsareallowedviathisAbstractsecurityinterceptor.n17.+"Thisindicatesaconfigurationerrorbecausethe"18.+"AbstractSecuritylnterceptor.rejectPublicInvocationspropertyissetto'true'")Ç19.)20.21.if(logger.isDebugEnabled()){22.logger.debug("Publicobject-authenticationnotattempted**);23.)24.25.publishEvent(newPubliclnvocationEvent(object));26.27.returnnull;//nofurtherworkpost-invocation28.)29.30.31.if(logger.isDebugEnabled()){32.logger.debug("Secureobject:"+object.toString()+ConfigAttributes:"+attr.toString0)Ç33.)34.஻$8SecurityContextHolder¥9Authenticationi¦ᙠ§¨Z\ᑮSecurityContextHolderi

8835.if(SecurityContextHolder.getContext().getAuthentication()==null){36.credentialsNotFound(messages.getMessage("AbstractSecuritylnterceptor.authenticationNotFound",37."AnAuthenticationobjectwasnotfoundintheSecurityContext"),object,attr);38.}39.40.஻᝞.©☢/ᨵᜐᳮ␺ᩗ$8◤⌕␺ᩗPQᜐᳮ41.Authenticationauthenticated;42.43.if(!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()||alwaysReauthenticate){44.try{஻ᵨrtḄAuthenticationManagerᜐᳮ␺ᩗ᝞.␺ᩗ<ᡂI4567®ᜐᳮ45.authenticated=this.authenticationManager.authenticate(SecurityContextHolder.getContext()46..getAuthentication());47.}catch(AuthenticationExceptionauthenticationException){48.throwauthenticationException;49.}50.51.//Wedon'tauthenticated.setAuthentication(true),becauseeachprovidershoulddothat52.if(logger.isDebugEnabledO){53.logger.debugC'SuccessfullyAuthenticated:"+authenticated.toStringO);54.)55.//$8g␺ᩗᡂIᑮḄAuthentication¯°ᑮSecuhtyContextHolderjAᵨ56.SecurityContextHolder.getContext().setAuthentication(authenticated);57.}else{஻$8ᜐᳮ©☢²³´%␺ᩗḄVWᐜSecurityContextHolder¥9Authentication58.authenticated=SecurityContextHolder.getContext().getAuthentication();59.60.if(logger.isDebugEnabledO){61.logger.debug("PreviouslyAuthenticated:"+authenticated.toString());62.}63.}64.65.஻$ᜐᳮᣴᩗḄ%&66.try{67.஻ᵨrtḄAccessDecisionManagerᩭPQᣴᩗ68.this.accessDecisionManager.decide(authenticated,object,attr);69.}catch(AccessDeniedExceptionaccessDeniedException){70.஻ᣴᩗ<ᡂIᔣ᜜·¸¹º71.AuthorizationFailureEventevent=newAuthorizationFailureEvent(object,attr,authenticated,72.accessDeniedException);73.publishEvent(event);

8974.75.throwaccessDeniedException;76.}77.78.if(logger.isDebugEnabledO){79.logger.debug("Authorizationsuccessful");80.}81.82.AuthorizedEventevent=newAuthorizedEvent(object,attr,authenticated);83.publishEvent(event);84.85.//$8᪀¼iRunAsManagerᩭ½(¾©ḄAuthentication¿ÀÁÂAᵨḄNullRunAsManagerZgSecurityContextHolderḄAuthenticationÅÆ86.AuthenticationrunAs=this.runAsManager.buildRunAs(authenticated,object,attr);87.88.if(runAs==null){89.if(logger.isDebugEnabledO){90.logger.debug("RunAsManagerdidnotchangeAuthenticationobject");91.)92.93.//nofurtherworkpost-invocation94.returnnewlnterceptorStatusToken(authenticated,false,attr,object);95.}else{96.if(logger.isDebugEnabledO){97.logger.debug("SwitchingtoRunAsAuthentication:"+runAs.toStringO);98.}99.100.SecurityContextHolder.getContext().setAuthentication(runAs);101.102,//reverttotoken.Authenticatedpost-invocation103.returnnewlnterceptorStatusToken(authenticated,true,attr,object);104.}105.}ᑮ$8ᡃqᎷrAffirmativeBased~AccessDecisionManagerJava(ṹ1.஻$8ÉÊNËÌÍᑴ◤⌕ᐰἠÐÑ´%2.publicvoiddecide(Authenticationauthentication,Objectobject,ConfigAttributeDefinitionconfig)3.throwsAccessDeniedException{4.஻$89rtḄÒ(ᘤᔠ5.Iteratoriter=this.getDecisionVoters().iterator();6.intdeny=0;7.஻ÓAᵨᔜᢗἠᘤPQᢗἠ^ᢗἠ.PQÕἠ

908.while(iter.hasNext()){9.AccessDecisionVotervoter=(AccessDecisionVoter)iter.next();10.intresult=voter.vote(authentication,object,config);11.஻$ᢗἠ.PQᜐᳮ᝞.⍗ᑮᐸiἠ´%Øᣴᩗ´%᝞.ÙᩗᡈὅÜØÝÞᢗἠ12.switch(result){13.caseAccessDecisionVoter.ACCESS_GRANTED:14.return;15.16.caseAccessDecisionVoter.ACCESS_DENIED:17.஻$8ÜἠPQÕᦪ18.deny++;19.20.break;21.22.default:23.break;24.)25.)26.஻᝞.ᨵÜἠ4567᦮ᣴᩗ<´%27.if(deny>0){28.thrownewAccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",29."Accessisdenied"));30.)31.32.஻$8ÙᩗἠPQᜐᳮᐰÙᩗἠḄËÉÁ¿À<´%ᵫallowlfAIIAbstainDecisionsàáâᑴ33.checkAllowlfAIIAbstainDecisions();34.)35.ᐹoḄᢗἠᵫᢗἠᘤPQᡃq$8r.NRoleVoterᩭPQᢗἠ36.publicintvote(Authenticationauthentication,Objectobject,ConfigAttributeDefinitionconfig){37.intresult=ACCESS_ABSTAIN;38.஻$89£¤Ḅᐰr39.Iteratoriter=config.getConfigAttributes();40.41.while(iter.hasNext()){42.ConfigAttributeattribute=(ConfigAttribute)iter.next();43.44.if(this.supports(attribute)){45.result=ACCESS_DENIED;46.47.//$8£¤rḄᐰᣴᩗãäPQᑨ;åᓛrROLE©çḄè⁐r

9148.஻êᔊìr¡ឋ᝞.ᐸᓛríîoᢝᨵḄGrantedAuthoiity,ᑣïð[ᐕò஺49.for(inti=0;i0){

9228.thrownewAccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",29,"Accessisdenied"));30.}31.32.஻$8ÙᩗἠPQᜐᳮᐰÙᩗἠḄËÉÁ¿À<´%ᵫallowlfAIIAbstainDecisionsàáâᑴ33.checkAllowlfAIIAbstainDecisions();34.)35.ᐹoḄᢗἠᵫᢗἠᘤPQᡃq$8rNRoleVoterᩭPQᢗἠ36.publicintvote(Authenticationauthentication,Objectobject,ConfigAttributeDefinitionconfig){37.intresult=ACCESS_ABSTAIN;38.஻$89£¤Ḅᐰr39.Iteratoriter=config.getConfigAttributes();40.41.while(iter.hasNext()){42.ConfigAttributeattribute=(ConfigAttribute)iter.next();43.44.if(this.supports(attribute)){45.result=ACCESS_DENIED;46.47.஻$8£¤rḄᐰᣴᩗãäPQᑨ;åᓛrROLE©çḄè⁐r48.//êᔊìr¡ឋ᝞.ᐸiᓛríîoᢝᨵḄGrantedAuthoiity,ᑣïð[ᐕò஺49.for(inti=0;i

93

94$tomcat6.xḄ¤(ṹorg.apache.catalina.session.StandardSessionAᵨ᝞Ḅ᪀ᩭ°ùsessionḄúprotectedMapattributes=newGoncurrentHashMapO;ᙠpublicvoidsetAttribute(Stringname,Objectvalue)8▭ᵨNsetAttribute(name,value,true);ᙠpublicvoidsetAttribute(Stringname,Objectvalue,booleannotify)8᝞.value0,ᑣᵨremoveAttrbuteü,þ¡ឋÿ◀if(value==null){removeAttribute(name);return;)ᔲᑣᵨObjectunbound=attributes.put(name,value);ᦪᑮ☢ᑮḄᡃᩭpublicvoidremoveAttribute(Stringname,booleannotify)ᵨprotectedvoidremoveAttributelntemal(Stringname,booleannotify)//AvoidNPE=NullPointerExceptionᕣᕣᢣ┐if(name==null)return;//Removethisattributefromourcollection//ᓫḄ"Map☢ᑤ◀Objectvalue=attributes.remove(name);//$☢%ᨵ'()*+,Ḅ-.ᵨ/0ᙠSessionᡃ2ᵨḄ345678Ḅ9ᨵ:6;<Ḅ=>஺@⌕ᡃBᑮCDᡃḄsessionEF/ᑮᡃᙠ☢Ḅ=>஺SyndContentlmpl.value=G⚪I

95JKLwebMNOPDtomcatQRwebMNQḄSKL'TᙠUV(ᡈYZ[\UV)ᐵ_tomcat$RwebMN9ᨵZᐵᣵ(windowsabQ⊤8dtomcat.exeeLfgᐵ_java.exeeLhiᙠjkᙠlm᡻V)op-.Iqr'stuvRv78ServletContextListenerxyQḄcontextlrdtiialized()-.zcontextDestroyed()-.஺ᯠ$ᙠtomcatQ|}Rtuv~ᡈᐵ_tomcatᐜ᡻VRtuv1ஹ:qrtuvCgmlndexListenerpackagecom.saas.cgm;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;஻ᵨServletContextListenerxy/B◤javax.servlet-5.L12.jarᡈᐸpublicclassCgmlndexListenerimplementsServletContextListener{privatestaticExecutorServiceexec=Executors.newCachedThreadPool();஻KL//ᐵ_tomcatᐵ_KLpublicvoidcontextDestroyed(ServletContextEventargO){exec.shutdownNow();;}//~tomcat᡻VKLpubliccontextInitiialized(ServletContextEventargO){RamlndexWriterramlndexWriter=newRamlndexWriter஺;//qr'sKLexec.execute(ramlndexWriter);}2ஹ|}RtuvIᙠtomcatḄconfᦻ*ᜳᑁḄweb.xmlᦻ*QIcom.saas.cgm.CgmIndexListener᝞ᡠIdefault/jsp*.jspjsp*.jspxv!--ᙠᓃ¢$com.saas.cgm.CgmIndexListener3ஹ£ᐵ_tomcattomcat✌ᐜᐵ_KLexecQḄramlndexWriterKL¥9ᨵSKLᙠUVjava.exeeL¦BZ§ᑭᐵ_

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
最近更新
更多
大家都在看
近期热门
关闭