Spring源代码解析

Spring源代码解析

ID:83420718

大小:18.58 MB

页数:125页

时间: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源代码解析》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

Springṹ᪆()IOCᘤᙠRod.JohnsonḄீீProfessionalJavaDevelopmentwiththespringframeworkு,ṹ⍝"#$%&Ẉ(᳝%ᨵᐶ,Ḅ-./01Ẇ#ᔳ456ᑁ(89:httpᑁ/jiwenke-spring.blogspot,com/,;<ᢣ>)ᙠSpring?%IOCᘤḄ@⌕ᙢCᡃEFGHI%JKSpringḄLᵨὅOP%I0CᘤQ▭STUVᕖXᡃEY5IBeanFactoryFTᡃEᑮḄIoCᘤ%[ᯠSpring]ᡃE^ᜓ`HaIoCᘤᩭLᵨ%c᪵Y5eᡃEfG-Ḅg☢%G-ḄiCj%G-ḄklḄmnopᩭqrᡃE◤⌕ḄIoCᘤ஺ᙠSpring?%ᨬvwḄI0CᘤxyTBeanFactory-c"xy]ᐹ{ḄI0CᘤḄQ|}ᨬvwḄ~m-GVḼ%}]I0Cᘤ%cxy⌕ᵨḄᨬvw⌕JavaṹN1.publicinterfaceBeanFactory{2.஻cTJFactoryBeanḄnmn%]᝞LᵨbeanḄFactoryBeanᑮḄJTᔆᡂḄJ%3.஻᝞◤⌕ᑮᔆw%◤⌕n4.StringFACTORY_BEAN_PREFIX=5.஻c᪷¡beanḄ¢%ᙠI0Cᘤ?ᑮbeanQ£%c"I0CᘤFT"ᜧḄ¥ᔆ஺6.ObjectgetBean(Stringname)throwsBeansException;7.஻c᪷¡beanḄ¦Class§¨ᩭᑮbeanQ£%¦S☢Ḅe©G-ᙠKª«&¬®᝞᪷¡¯ḄbeanQ£ḄClass§¨¦◤⌕ḄG-Ḅ°஺8.ObjectgetBean(Stringname,ClassrequiredType)throwsBeansException;9.10.஻c±²JbeanḄ%TᔲᙠIOCᘤᨵc"Ḅbean11.booleancontainsBean(Stringname);12.13.஻c᪷¡beanᑮbeanQ£%´-µᑨ·c"beanTGTᓫ¹14.booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;15.16.஻cJᑮbeanQ£ḄClass§¨17.ClassgetType(Stringname)throwsNoSuchBeanDefinitionException;18.19.஻cᑮbeanḄº%᝞᪷¡º%»Vᐸ½«¾¬ᩭ20.String1]getAliases(Stringname);

121.22.)ᙠBeanFactory¿JIOCᘤḄvwÀ]}mn%᪷wGᐵÂḄbeanT᪵mn᪵ÃÄḄ-FÅᡃE¿ᐵÂfc"ᔆᡃEᑮᑮUVÆÇJ%ÈKᔆTVÆcJḄ%c"vwḄxyGᐵÂc஺᝞⌕ᐵÂᔆT᪵ÆJḄ%Éᵨ◤⌕Lᵨᐹ{ḄI0CᘤQ|-[ᯠY58Ê᪷¡c"BeanFactoryᩭQ|8ÊḄI0Cᘤ%Ëc"Ìᨵ⌕%]SpringÍÎ]ᡃE^ᜓÏÐᑡᔆᩭÒᡃELᵨ஺Ó᝞XmlBeanFactoryFT┐JᨬvẠḄBeanFactoryḄI0CᘤḄQ|-c"Q|LᵨxmlᩭmnI0Cᘤ?ḄbeanoSpring±²"BeanFactoryḄvwQ|%XmlBeanFactory-᪵ḄÖ×LᵨØÙØlᩭᑮJI0CᘤḄ¥-AbstractBeanFactory,DefaultListableBeanFactoryc¥§]ᐸ±²ØÙÚÛ஺ᐸ?Ö×resourcexyᩭ¥beanmnᦪ¡%JXmlmnᦻ¹Ḅ᪆Ö×ÞᡲàXmlBeanDefinitionReaderᩭáᡂ஺6☢ᡃE᪷¡âSḄ£ã%äᓫḄåæI0CçᘤḄèq×JavaṹO1.ClassPathResourceres=newClassPathResource("beans,xml஻)B2.DefaultListableBeanFactoryfactory=newDefaultListabieBeanFactory();3.XmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(factory);4.reader.loadBeanDefinitions(res);cṹåæ56é"êë1.èqIOCìjᦻ¹Ḅ¥i2.èq"BeanFactory3.íî¯ìjopḄBeanDefinitionReader,cTXmlBeanDefinitionReaderìjàBeanFactory4.fmnÏḄiCjîᐭìjop%ᐹ{Ḅ᪆×ᵫXmlBeanDefinitionReaderᩭáᡂ%c᪵áᡂ᦮"ÄᐭbeanmnḄ×஺ᡃEḄIoCᘤòqr/ᩭ஺ᙠBeanFactoryḄṹ?ᡃEY5ᑮJavaṹó1.publicclassXmlBeanFactoryextendsDefaultListableBeanFactory{2.஻c]ᘤmn"ôLᵨḄbeanmnî¯ᘤ3.privatefinalXmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(this);

24.publicXmlBeanFactory(Resourceresource)throwsBeansException{5.this(resource,null);6.)7.஻ᙠ!ᓄ#ᦪ%&ᵨ()ᘤᩭ,-./0()12ᑮbean5678஺8.publicXmlBeanFactory(Resourceresource,BeanFactoryparentBeanFactory)throwsBeansException{9.super(parentBeanFactory);10.this,reader.loadBeanDefinitions(resource);11.)ᡃDᙠE☢GHᑮ()ᘤ()-.IJKbean5678Ḅ᦮NOP1QRSTISUᦻḄᜐᳮTY᪵Ḅ1[\]ᡃD^_HᑮSUᦻIXmlBeanFactory\`aI0CdᘤḄef1BeanFactorygghᐹᜓ,-.56Ḅkl1mSUᦻ^_nopᡂ-.561[\NrsSHSUᦻtuᵨYv஺wxᑖ᪆SpringBeanFactoryḄ}᪀1ᡃDᩭHHᙠBeanFactoryQẠS᡽ḄApplicationcontext-ᡃDᨬ&ᵨḄSUᦻ஺◀ᐹᜓBeanFactoryḄᐰkl1SUᦻᵨPᑭ*^_ᢝhḄ78.1ᡃDHᑮApplicationContext᡽MessageSource*-.1ᙠ,ResourceLoaderIResourceḄᢝS☢1\᪵ᡃD^_[hᙢ¡2ᑮbean56-.*ᢝᵨ¢£1¤¥¦§ApplicationEventPublisher,\᪵ᙠSUᦻ%ªᐭ¢£¬ᑴmBeanFactoiryT®ᨵḄ஺ApplicationContextᐕSUᦻ±ᝅ-³O´ᢝ᱄SUᦻ^_¶ᢝYNSUᦻ·-\N·ᡃDᙠ_E,Webdᘤ%ḄSUᦻ¹᛻Ḅᑖ᪆%^_»¼ᙢHᑮ஺,½beanḄ¾¿^_ᙠ\NSUᦻ·%ÀÁ1✌ᐜľÅÆSUᦻ1ᐸÈT᱄SUᦻ1⌲ÊᔣS1\᪵hḄSpringᵨÌÍYNᐳÏḄbean56¹᛻஺\NᡃDᙠᑖ᪆Webdᘤ%ḄSUᦻ¹᛻ÐÑkHᑮ஺ApplicationContextÌÍIoCdᘤḄÒ⌕¦§1ᙠᐸ·%ᨵÔÕÖ×Ø᝞AbstractApplicationContextᐹḄBeanFactoryḄÚ1Ø᝞FileSystemXmlApplicationContextIClassPathXmlApplicationContextÌÍSUᦻḄÛÜ1&2ÝDÞ◤⌕ᐵáᐹḄ-.5â⚪஺ÅᵨPäṹÚæᓄFileSystemXmlApplicationContextḄÐ᎛12ᑮIoCdᘤḄYaᐹ⊤-ApplicationContext,[mᵨP³OApplicationContextᩭéᳮ,beanḄêë஺BeanFactoryTYN¦§1ᙠÚ▭ᵨ%ᡃDYí&ᵨApplicationContextᩭ&ᵨI0Cdᘤ1îDÑTI0CdᘤïᵨðÀὅḄ&ᵨ¦§஺,ᵨPðÀὅᩭò1^_óBeanFactoryIApplicationFactoryᙠhḄ&ᵨô☢Sä⊤SPRINGÌÍḄI0Cdᘤ÷ø஺

3U☢ᡃDᐹHH³OFileSystemXmlApplicationContextTù᪵úûüI0CdᘤḄ1ým᧕ÿᡃnewᩭᑮIoCᘤJavaṹ1.ApplicationContext=newFileSystemXmlApplicationContext(xmlPath);-ᵨḄ0123ᓄṹ:JavaṹI'J1.publicFileSystemXmlApplicationContext(String1]configLocations,booleanrefresh,ApplicationContextparent)2.throwsBeansException{3.super(parent);4.this,configLocations=configLocations;5.if(refresh){6.஻HI0IoCᘤḄ23ᓄJKᐸ23ᓄJḄᜧNOPᵫAbstractApplicationContextᩭRS7.refresh();8.)9.)refreshḄWXᙠAbstractApplicationContext:JavaṹIJ1.publicvoidrefresh()throwsBeansException,IllegalStateException{2.synchronized(this.startupShutdownMonitor){3.synchronized(this.activeMonitor){4.this,active=true;5.)6.7.//HI◤⌕`aᩭbcdᡂfghiRS,beanjᐭlᔣI0CᘤopḄJ8.refreshBeanFactory();9............................10.}Hrstᒹvw᦮rBeanFactory23ᓄḄJKyzᱯRḄFileSystemXmlBeanFactory,ᡃ|ᑮRhfghiᵫrefreshBeanFactory()ᩭ}~

4ᙠAbstractXmlApplicationContextRSwyfgḄJKᵫXmlBeanDefinitionReaderᩭJavaṹ1.protectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwslOException{2.//HIᵨXMLBeanDefinitionReaderᩭjᐭbeanRSḄXMLᦻ3.XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);4.5.஻HIireaderḄ᛻KᐸResourceLoader0ᡃᵨᩭRhbeanRSfghiḄ6.஻/ᦻ}~wResourceLoaderKᡠᦻResourceLoader⌴XmlBeanDefinitionReader7.beanDefinitionReader.setResourceLoader(this);8.beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));9.10.initBeanDefinitionReader(beanDefinitionReader);11.஻HIᑮRSḄXmlBeanDefinitionReaderyjᐭbeanᜐᳮ12.loadBeanDefinitions(beanDefinitionReader);13.}ᑮbeanDefinitionReaderᜐᳮ:JavaṹI¡1.protectedvoidloadBeanDefinitions(XmlBeanDefinitionReaderreader)throwsBeansException,lOException{2.Resource[]configResources=getConfigResources();3.if(configResources!=null){4.஻-ᵨXmlBeanDefinitionReaderᩭjᐭbeanRS஺5.reader.loadBeanDefinitions(configResources);6.)7.String[]configLocations=getConfigLocations();8.if(configLocations!=null){9.reader.loadBeanDefinitions(configLocations);10.

511.)£ᙠᐸ¤¥᱄aḄAbstractBeanDefinitionReaderᩭRSjᐭJ:Javaṹ!J1.publicintloadBeanDefinitions(Stringlocation)throwsBeanDefinitionStoreException{2.஻HIᑮª«RSḄResourceLoader,ḄᡃᵨDefaultResourceLoader3.ResourceLoaderresourceLoader=getResourceLoader();4஻᝞®ᨵ°ᑮᡃ◤⌕ḄResourceLoader,±²³´5.if(resourceLoaderinstanceofResourcePatternResolver){6.//HIᜐᳮᡃᙠRShiµᵨḄᔜ·pattern,◤⌕ResourcePatternResolverᩭdᡂ7.try{8.Resource[]resources=((ResourcePatternResolver)resourceLoader).getResources(location);9.intloadCount=loadBeanDefinitions(resources);10.returnloadCount;11.12.13.)14.else15.//HIResourceLoaderᩭdᡂhiRh16.ResourceresourceresourceLoader.getResource(location);17.//HI¹º»rhiRSᓄResource,¼XmlBeanDefinitionReaderᩭᵨw18.intloadCount=loadBeanDefinitions(resource)½19.returnloadCount;20.21.)ªᡃResourceLoaderᩭjᐭfgK¾¿wwᡃḄGenericApplicationContextÁ}~wResourceLoaderJavaṹTj1.publicclassGenericApplicationContextextendsAbstractApplicationContextimplementsBeanDefinitionRegistry{

62.publicResourcegetResource(Stringlocation){3.஻HI-ᵨª«ḄloaderÁÄ0DefaultResourceLoaderᩭdᡂjᐭ4.if(this.resourceLoader!=null){5.returnthis.resourceLoader.getResource(location);6.)7.returnsuper.getResource(location);8.)9........10.)£ᡃḄFileSystemXmlApplicationContextÄ0»rDefaultResourceLoader-GenericApplicationContextDefaultResourceLoader:JavaṹI-'J1.publicResourcegetResource(Stringlocation){2.஻᝞0aÆÇḄsÈKÉ◤⌕ᵨClassPathResourceᩭᑮbeanᦻḄfgy¥3.if(location.startsWith(CLASSPATH_URL_PREFIX)){4.returnnewClassPathResource(location,substring(CLASSPATH_URL_PREFIX.length()),getClassLoader());5.)6.else{7.try{8.//᝞0URLsÈKᵨUrlResourcebeanᦻḄfgy¥9.URLurl=newURL(location);10.returnnewUrlResource(url);11.)12.catch(MalformedURLExceptionex){13.//᝞ÎÏ0KÉᡃÐÑÒᡲ`aᵫ`aᩭÔRᵨÕÖ᪵Ḅfgy¥w14.returngetResourceByPath(location);15.)16.)17.)ᡃḄFileSystemXmlApplicationContextÄ00DefaultResourceLoaderḄ}~aKØ}~wḄJavaṹṹ

71.protectedResourcegetResourceByPath(Stringpath){2.if(path!=null&&path.startsWith(஻/஻)){3.path=path,substring(1);4.)5.஻HIᵨᦻÚÛfgy¥ᩭRSbeanᦻ6.returnnewFileSystemResource(path);7.)H᪵ṹÄÜᑮwFileSystemXmlApplicationContextᩭKØݼwFileSystemResourceᩭdᡂÞᦻÚÛᑮiᦻḄfgRS஺H᪵KÄÞᦻÚÛÆÇyI0Ciᦻßj-ªᯠᡃᢥ᯿HrãäÞåæᙢsßjKᙠSpringᡃ|ᑮ1ݼḄᔜ·fg¤¥Kè᝞ClassPathResource,URLResource,FileSystemResourceéᩭ¼ᡃᵨ஺☢ᡃ|ᑮḄ0RhResourceḄ»rJK£HÐ0ßjJḄ»ëᑖ-ᡃÜíUAbstractBeanDefinitionReaderzḄloadDefinitions(resource)ᩭ||ᑮ⊤beanᦻḄfgRSïḄjᐭJ,ḄᡃᵨXmlBeanDefinitionReaderJavaṹ£1.publicintloadBeanDefinitions(EncodedResourceencodedResource)throwsBeanDefinitionStoreException{2...............3.try{4.஻HIResourceᑮInputStreamḄ10ð5.InputStreaminputstream=encodedResource.getResource().getInputStream();6.try{7.஻ÞInputStreamᑮXMLḄñ᪆g8.InputSourceinputSource=newInputSource(inputStream);9.if(encodedResource.getEncodingO!ônull){10.inputSource.setEncoding(encodedResource.getEncodingO);11.)12.஻HI0ᐹöḄñ᪆lopJ13.returndoLoadBeanDefinitions(inputSource,encodedResource.getResource());14.}15.finally{16.஻ᐵøÞResourceᑮḄ10ð17.inputStream.close();18.}

819.)20...............21.)22.23.protectedintdoLoadBeanDefinitions(InputSourceinputSource,Resourceresource)24.throwsBeanDefinitionStoreException{25.try{26.intvalidationMode=getValidationModeForResource(resource);27.஻ñ᪆ᑮDOM,ᯠïdᡂbeanᙠIOCᘤḄop28.Documentdoc=this.documentLoader.loadDocument(29.inputSource,this.entityResolver,this.errorHandler,validationMode,this,namespaceAware);30.returnregisterBeanDefinitions(doc,resource)*31.)32........33.)ᡃ|ᑮᐜRSᦻñ᪆DOMy¥KᯠïᐹöḄopJ:Javaṹᵨ1.publicintregisterBeanDefinitions(Documentdoc,Resourceresource)throwsBeanDefinitionStoreException{2.//HIRSñ᪆ᘤKᵨXmlBeanDefinitionParserᩭñ᪆xmlsÈḄbeanRSᦻ-~ᙠḄ᱐ÏᵨHrñ᪆ᘤwKᵨḄ0XmlBeanDefinitionReader3.if(this.parserClass!=null){4.XmlBeanDefinitionParserparser=5.(XmlBeanDefinitionParser)BeanUtils.instantiateClass(this.parserClass);6.returnparser.registerBeanDefinitions(this,doc,resource);7.)8.//ᐹöḄopJK✌ᐜᑮXmlBeanDefinitionReader,ᩭᜐᳮxmlḄbeanRSᦻ9.BeanDefinitionDocumentReaderdocumentReader=createBeanDefinitionDocumentReader();

910.intcountBefore=getBeanFactory().getBeanDefinitionCount();11.documentReader.registerBeanDefinitions(doc,createReaderContext(resource));12.returngetBeanFactory0.getBeanDefinitionCount()»countBefore;13.)ᐹöḄᙠBeanDefinitionDocumentReaderdᡂyK☢0»rü⌕ḄopJᩭdᡂbeanRSᦻḄñ᪆lI0CᘤbeanḄ23ᓄJavaṹ!:J1.publicvoidregisterBeanDefinitions(Documentdoc,XmlReaderContextreaderContext){2.this.readerContext=readerContext;3.4.logger,debug("Loadingbeandefinitions");5.Elementroot=doc.getDocumentElement();6.7.BeanDefinitionParserDelegatedelegate=createHelper(readerContext,root);8.9.preProcessXml(root);10.parseBeanDefinitions(root,delegate);11.postProcessXml(root);12.)13.14.protectedvoidparseBeanDefinitions(Elementroot,BeanDefinitionParserDe1egatedelegate){15.if(delegate.isDefaultNamespace(root.getNamespaceURI()))(16.஻HIᑮxmlᦻḄ`⁚᝞ᔜbean⁚17.NodeListnl=root.getChildNodes();18.19.஻"#$%⁚&'ᑖ᪆ᜐᳮ20.for(inti=0;i

1024.StringnamespaceUriele.getNamespacellRI();25.if(delegate,isDefaultNamespace(namespaceUri)){26.஻"#BC᪆DEḄGᵨ,$IḕḄᐗL&'ᑖ᪆᝞beanᐗL27.parseDefaultElement(ele,delegate);28.)29.else30.delegate.parseCustomElement(ele);31.)32.)33.)34.}else{35.delegate.parseCustomElement(root);36.}37.)38.39.privatevoidparseDefaultElement(Elementele,BeanDefinitionParserDelegatedelegate){40.஻"#$ᐗLImport&'ᜐᳮ41.if(DomUtils.nodeNameEquals(ele,IMPORT_ELEMENT)){42.importBeanDefinitionResource(ele);43.)44.elseif(DomUtils.nodeNameEquals(ele,ALIAS_ELEMENT))(45.Stringname=ele.getAttribute(NAME_ATTRIBUTE);46.Stringalias=ele.getAttribute(ALIAS_ATTRIBUTE);47.getReaderContext().getReader().getBeanFactory().registerAlias(name,alias);48.getReaderContext().fireAliasRegistered(name,alias,extractsource(ele));49.)50.஻"#$ᡃZᨬ\៉ḄbeanᐗL&'ᜐᳮ51.elseif(DomUtils.nodeNameEquals(ele,BEAN_ELEMENT))(52.஻^ᡲ`BeanDefinitionParserDelegateᩭbᡂ$beanᐗLḄᜐᳮ"dᒹfgᐹiḄbeanC᪆ḄDE஺

1153.//lC᪆beanᦻnoᑮḄqrsᑮBeanDefinition#tBbeanqrḄu⌕wixBI0CyᘤḄ{ᳮ$|஺54.BeanDefinitionHolderbdHolder=delegate,parseBeanDefinitionElement(ele);55.if(bdHolder!=null){56.bdHolder=delegate.decorateBeanDefinitionIfRequired(ele,bdHolder);57.//"#BᔣIOCyᘤ▭BsᑮIOCyᘤḄmap#58.BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry());59.60.//"#ᔣIOCyᘤ〈n⊤C᪆bᡂ஺61.getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolder));62.}63.64.)ᡃZᑮᙠparseBeanDefinition$ᐹibeanᐗLḄC᪆`BeanDefinitionParserDelegateᩭbᡂḄ☢ᡃZC᪆bḄbeanB᪵ᙠI0CyᘤḄᙠBeanDefinitionReaderUti1sGᵨḄBJavaṹ1.publicstaticvoidregisterBeanDefinition(2.BeanDefinitionHolderbdHolder,BeanDefinitionRegistrybeanFactory)throwsBeansException{3.4.//"#oᑮ◤⌕beanḄ5.StringbeanName=bdHolder.getBeanName();6.஻"BGᵨIOCᩭḄbeanḄDE◤⌕oᑮBeanDefinition7.beanFactory.registerBeanDefinition(beanName,bdHolder.getBeanDefinition());8.9.//xB¡DIOCyᘤbeanὶ£¤ᩭḄ&'10.String[]aliases=bdHolder.getAliasesO;11.if(aliases!=null){12.for(inti=0;i

1213.beanFactory.registerAlias(beanName,aliases[i]);14.)15.)16.)ᡃZXmlBeanFactoryḄ¨:JavaṹIJ1.//---------------------------2.//"#BIOCyᘤ$BeanDefinitionRegistry«¬Ḅ¨3.//---------------------------------------------------4.5.publicvoidregisterBeanDefinition(StringbeanName,BeanDefinitionbeanDefinition)6.throwsBeanDefinitionStoreException{7.8.............஻"#ḕᶍg$BeanDefinitionḄ®¯DE9.஻ᐜᙠyᘤ#B±B²³ᨵgµḄbean,᝞¶ᨵ·¸¹º஺10.ObjectoldBeanDefinition=this.beanDefinitionMap.get(beanName);11.if(o1dBeanDefinition!=null){12.if(!this,allowBeanDefinitionOverriding){13..........................14.)15.else{16.஻lbeanḄ¼ᑮIOCyᘤ½17.this.beanDefinitionNames.add(beanName);18.)19.஻"#lbeanḄBean¾¿ὶ£¤ᩭsᑮHashMap½I0Cyᘤ¡D"MapᩭÀÁyᘤ#ḄBean¾¿qr஺20.this.beanDefinitionMap.put(beanName,beanDefinition);21.removeSingleton(beanName);22.)"᪵ÂbᡂgBean¾¿ᙠIOCyᘤḄÂÃIOCyᘤ&'{ᳮÄᵨg஺Å☢ḄṹᩭᡃZÆÇI0CyᘤÈÉᓄḄËÌÍÎ

13*ÈÉᓄḄᐭ¬ᙠyᘤ¨Ḅrefresh஺Gᵨᩭbᡂ*$bean¾¿wᐭIOCyᘤÄᵨḄÑÒBloadBeanDefinition,ᐸḄᜧÕDE᝞¡DResourceLoaderᩭbᡂÖ×ᦻnØÙḄ¾ØDefaultResourceLoaderBÚÛḄ¨µÜᦻÌÝÂ`¸gResourceLoaderḄ¨ÅdÞßᦻn£àURLáÑᩭ¾âÖ×ØÙ஺᝞¶BXmlBeanFactoryãâI0Cyᘤäå◤⌕âæᢣ¾bean¾¿ḄÖ×xÂBèbean¾¿ᦻnÜ¡Dé|ᡂResourceᩭÃI0CyᘤᜐᳮḄyᘤ¡DBeanDefinitionReaderᩭbᡂ¾¿qrḄC᪆BeanqrḄêêÄᵨḄBXmlBeanDefinitionReaderᩭC᪆beanḄxml¾¿ᦻn-▭ḄᜐᳮDEB^ᡲ`BeanDefinitionParserDelegateᩭbᡂḄÅëoᑮbeanḄ¾¿qr"ìqrᙠSpringÄᵨBeanDefinition$|ᩭ⊤-"íᡃZîᑮloadBeanDefinition,RegisterBeanDefinition"ìïᐵḄÑÒ-tZñBâᜐᳮBeanDefinitinòóḄIoCyᘤC᪆oᑮBeanDefinitionô◤⌕læᙠI0Cyᘤ"ᵫI0C¨BeanDefinitionRegistry«¬ᩭ¨஺DEÂBᙠI0Cyᘤᑁ÷ÀÁḄHashMapᩭøùoᑮḄBeanDefinitionḄDE஺"HashMapBIoCyᘤᢝᨵbeanqrḄûᡠô$beanḄýãñBþÿHashMapᩭḄ஺*ᯠᡃBeanFactoryApplicationContextᩭᑮSpringIOCḄ.ᙠᵨI0CᘤḄ᎛ᡃ!"ᑮ◀$%&ᔠ(ṹ*ᜧ,ᦪ./IoC012ᑏḄ4ᵨ56(ṹ7ᐰ9ᵨᐵ;᝞=ᑮ>?ᔆABᘤCDEFGHᘤIᳮḄᐸLFGMᙠNO஺PQḄRᶍTD?ᔆUᑮVWḄᙢYᨬ[TUᙠF⚜]ᵨḄ^_ᦻᨵ"bḄᙢYc(ṹC▭◤⌕gh?ᔆḄᙢY஺SpringQijkFlmnoᐭweb4ᵨ56ᵨqḄ4ᵨ56^_ᦻrCᐸstᙠServletContextuḄ᪾w஺ᐹyz{Ḅᦻ|஺ᙠᵨSpringIOCᘤḄ᎛ᡃ}◤⌕~ᭆBeanfactoryFactorybean,ᐸuBeanFactoryᢣḄTIOCᘤḄ25G,᝞Applicationcontext,XmlBeanFactoryETI0CᘤḄᐹy⊤◤⌕ᵨ᪵ḄᘤᵫᡝSpringBᡃjkḄ⌱஺FactoryBeanTNᙠI0CᘤuIᳮḄNbean,TFᔜᜐᳮ5ᵨḄG,Factorybeanᙠ◤⌕¡¢NFG9£¤FactoryBeanQḕᡃD¦§ᡂTNG?ᔆF¦Ḅ©ᵨ£¤ḄT?ᔆ¡Ḅª஺ᡠᨵḄFactorybeanᱯḄorg.springframework.beans,factory.FactoryBean®¯°ᵨᘤufactorybeanḄ᎛±ᘤ9²£¤factorybeanQiT£¤ᐸ¡ᡂḄFG஺Springᒹ´ᜧµᑖḄᵨghGḄFactorybeanḄ,ᐸuᒹ´FJNDI·¸ḄᜐᳮF(ᳮFGḄᜐᳮF¹ឋ(ᳮḄᜐᳮFRMI(ᳮḄᜐᳮEᡃ§ᡂTᐹyḄ?ᔆ§ᡂTSPRINGBᡃ»¼[Ḅ?ᔆ஺½T¾SpringᵨG?ᔆ¿nBᡃÀᜓNÂᑡ?ᔆᩭ¡NEᱯḄFGÄ◀ᡃÅ?ÆÇḄ?Èᡃ⌕ᵨ◤⌕ᙠI0CᘤÉÊË[ÌÍYÎḄᵨ஺ᙠᡃᩭ§§ᙠSpringḄ¹ÏÐᑴSpringuᨵ3᪗À¹Ï

14ContextRefreshEvent,ContextCloseEvent,RequestHandledEventLApplicationEvent®¯ë᪵Ḅ᝞ì◤⌕íbî½◤⌕ApplicationEvent®¯z᯿ContextCloseEventḄᑴíðḄ¹ÏJava(ṹ1.publicclassContextClosedEventextendsApplicationEvent{2.3.publicContextClosedEvent(App1icationContextsource)(4.super(source);5.)6.7.publicApplicationcontextgetApplicationContext(){8.return(ApplicationContext)getSourceO;9.)10.)ApplicationEventPublishAware&'()*+,-ᘤ὚ᔠᑮApplicationContext2᪵4ᵨApp1icationContext᪾7ᩭ9⌴;<=<>,ᯠAᙠApplicationContextCDEFbeanGH(ᙠ<=<>ḄJC(&KὅMApplicationListener&ᦈ<>஺Q᝞S&4ᵨSpringḄScheduleTimerTask;TimerFactoryBean[\]^ᘤ]^_`<>(ᐹbcdeSpring᪾7fghJi஺TimerFactoryBeanjklmᔆbean,oᐸCḄSchedule?imerTaskrsᜐᳮAvw(cὃScheduleTimerTaskḄM,yᨬA{ᵨḄjjreḄTimerTask}JavaṹU1.publicvoidsetRunnable(RunnabletimerTask){2.this.timerTask=newDelegatingTimerTask(timerTask);3.)ᙠCwHkl]^,〈<>Ḅ(ᯠ]^ᘤ[ᐸḄ[(ᨵ}1.]MethodlnvokingTimerTaskFactoryBean]⌕᡻sḄᱯ]beanḄᱯ](o◤⌕rs]2.]TimerTask¡(extendsTimerTaskᩭ¢ᑮ(£^o◤⌕rs¤]ᯠA◤⌕]ᐹbḄ]^ᘤcᦪ(DEScheduledTimerTaskCḄcᦪ;

15timerTaskᩭ¦ᡂ(¨jy◤⌕]Ḅᐹb©ឋ(timerTaskjᙠ«☢®]FḄbeanJavaṹ1privateTimerTasktimerTask;23privatelongdelay=0;45privatelongperiod=0;67privatebooleanfixedRate=false;ᨬA(◤⌕ᙠApplicationContextC´µ(◤⌕¶ScheduledTimerTaskDEᑮFactoryBean-TimerFactoryBean,2᪵GᵫI0Cºᘤᩭ»ᳮ]^ᘤH஺c᯿TimerFactoryBeanḄ©ឋ(]ᑴk¾]^ᘤ஺Javaṹ¿1.publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{2.3.protectedfinalLoglogger=LogFactory.getLog(getClass());4.5.privateScheduledTimerTask[]scheduledTimerTasks;6.7.privatebooleandaemon=false;8.9.privateTimertimer;10.11...................12.}᝞Å⌕,〈^ÆᡃÈÉ◤⌕ᙠ]FḄScheduledTimerTasksCpublish]FḄ*+GH஺ᐹbcὃCḄM(2ÊÉjËᔠFactoryBeanḄÌᳮkÍÎÏ஺᝞ÅËᔠ*+;]^ᘤÐᑴ(ᡃÈÑÒḄMheartbeatÓÔÕÖ×(CwH2l(2lM▭ÙËᔠHSpring*+;]^ÐᑴḄ4ᵨl☢ḄÚÛ-ᯠHÜᨵI0CºᘤḄÚÛÓÝÞSpringßᵨᡃàá⌫ãᣵI0CḄåæ}×==================================2==================================SpringçṹÎ᪆Óé×}IoCºᘤᙠWebºᘤCḄê

16Ù☢ᡃÈᑖ᪆HIOCºᘤìíḄM(¨☢ᡃÈÔÔᙠᐺïḄwebð᛻C,SpringIOCºᘤjò᪵óôᐭ;ö[ᵨḄ஺÷ᓫḄù(ᙠwebºᘤC(ServletContext\SpringḄI0Cºᘤúûüýð᛻(oßḄþÿI0CᘤḄ஺ᐸ✌ᐜ◤⌕Ḅ᪷ᦻᦻᢝᨵḄᨵ!"ᦪ$%&'()ᱥ+ᳮᘤ-ᔜ/01஺ᙠᦻḄ3Ạ5webMVC<ᐵ>?ᨵᦻᩭA%BᑴᘤDEḄMVC᪵G᪀ᡂJ1KᓄḄᦻM᪀஺ᙠwebᘤNOSpringVᵨXYGᦻḄZX஺Spring[webVᵨ\]JᦻḄ᡽_`aWebApplicationContext:Javamṹᔣ1.publicinterfaceWebApplicationContextextendsApplicationContext{2.஻yz{Ḅ|}ᵨ~ᙠServletContext%&᪷ᦻ3.StringR00T_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebAppiicationContext.class.getNameO+”.ROOT”;4..............5.//WebApplicationContextᩭ◤⌕ᑮWebᘤḄServletContext6.ServletContextgetServletContext();7.)ḄNOZXSpring?ᵨḄXmlWebApplicationContext-ᦻ¢[ᙠwebᘤḄ᪷ᦻᘤ£ᩭᐹḄZXᙠ☢ᡃ§?¨©ᑖ᪆஺Javamṹ1.publicclassXmlWebApplicationContextextendsAbstractRefreshableWebApplicationContext{2.3./**5web®¯<ᐵḄ°±²³ᵨᩭ¢[Ḅ᪷ᦻbeanz{²³Ḅ%´°±*/4.publicstaticfinalStringDEFAULT_CONFIG_LOCATION=^/WEB-INF/applicationContext.xml”;5.publicstaticfinalStringDEFAULT_CONFIG_LOCATION_PREFIX="/WEBTNF/”;6.publicstaticfinalStringDEFAULT_CONFIG_LOCATION_SUFFIX=".xml”;7.8.஻ᡃ§»¼ᑮJ½៉ḄloadBeanDefinition,GÀᡃ§Á☢I0CᘤḄᑖ᪆᪵ÂÃÄXᙠᘤḄrefresh()ḄÅ᎛NO஺

179.protectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwslOException{10.஻~XmlWebApplicationContext,ÉᯠᵨḄXmlBeanDefinitionReaderᩭbeanz{²³ᩭËÌÍ᪆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.)22.஻ᵨXmlBeanDefinitionReaderᩭÏᐭbeanz{²³23.protectedvoid1oadBeanDefinitions(XmlBeanDefinitionReaderreader)throwsBeansException,lOException{24.Stringf]configLocations=getConfigLocations();25.if(configLocations!=null){26.for(inti=0;i

1837.returnnewString[]{DEFAULT_CONFIG_LOCATION};38.)39.)40.)~Spring×ØḄwebVᵨXYÙZᵨSpringmṹÚÛÜḄᢣzᙠwebVᵨXYNOÅÃᐭVᵨXYᦻ(WebApplicationContext),SpringḄContextLoader\]᪵ឋßḄEᡃ§ᵨContextLoaderServletᡈὅContextLoaderListenerḄNOÅÃᐭḄServletᩭâᓄSpringIOCᘤ-[ãä?ᨵåæçḄEᩭèÃéᕖë[é§Ḅᵨ◤⌕ìíæçḄServletᘤîᢝḄSerlvet᱐ð஺ñæ+ContextLoaderSevlet>ContextLoaderListeneròᵨContextLoaderᩭóᡂ▭ḄWebApplicationContextḄõöᓄÄ¢஺ContextLoderGÀSpringWebVᵨXYᙠWebᘤḄÂÃᘤbooteroÉᯠ÷ServletḄᐹᵨᡃ§ò⌕øùwebᘤḄ®¯úûüᩭËÌ<ᐵḄz{஺☢ᡃ§ᵨContextLoaderListener¢[Ãᐭᘤ¢¨©Ḅᑖ᪆ServletḄýþᘤ᪷ᦻ£ÃᐭḄᙢÖÿ᦮SpringwebᵨᦻḄᙢᡃᑮ✌ᐜServletᑮServletContext,ᯠ!"ᑮ#$%Ḅᙠweb.xmlḄḄᔜ(ឋ*ᯠ!ContextLoder+,ᓄWebApplicationContext./ᡂᐸᐭ345ᓄ67᪷ᦻ஺:;᪷ᦻ<ᐭ!=<>?ᑮwebᵨ@ḄServletContext஺AB◤⌕EFGApplicationcontextḄᵨ@HṹJWebApplicationContextUtilsKḄ☟᝱NᩭᑮPJavaHṹ!:J1.WebApplicationContextgetWebApplicationContext(ServletContextsc)Tomcat67ServletQᘤ7,☢ᐹUḄVWP1.TomcatXYZ◤⌕web.xml"[XY\ᦪᙠweb.xmlᡃ◤⌕^ContextLoaderListener_`#$^aᙠwebᵨXYᐭbᙠContextLoaderListenerḄ45ᓄcᑖSpringMVC+▭ᙠwebQᘤfghiᑡḄI0CQᘤᐸᙠContextLoaderᐭḄI0CQᘤ67᪷ᦻklᙠaServletContext஺JavaHṹTj1.஻;o^᪷ᦻ_`45ᓄ஺2.publicvoidcontextInitialized(ServletContextEventevent){3.஻;opq◤⌕ḄContextLoader4.this.ContextLoader=createContextLoader();5.஻;orᵨContextLoader^᪷ᦻ_`ᐭ345ᓄ

196.this.contextLoader.initWebApplicationContext(event.getServletContext());7.)sContextLoaderqtu᪷ᦻḄᡃᙠContextLoaderᑮOJavaHṹ1.publicWebApplicationContextinitWebApplicationContext(ServletContextservletContext)2.throwsI1legalStateException,BeansException(3.஻;oᐜvwxᙠServletContextlᙠᦻ᝞zᨵ|}~☢wx<ᐭᡈὅ#$ᦻᨵ┯஺4.if(servletContext.getAttribute(WebApplicationContext.R00T_WEB_APPLICATION_CONTEXT_ATTRIBUTE)!=null){5.7/6.................7.)8.9.......................10.try{11.//;oᐭ᪷ᦻḄ᱄ᦻ12.ApplicationContextparent=loadParentContext(servletContext);13.14.஻;opq᪷ᦻ67᦮ᵨḄᦻZ=lᑮServletContext;orᵨḄServletContextḄ(ឋ*15.//ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,!ḄᵨJ᪷;(ឋ*[᪷ᦻḄ-67ᦻḄ᱄ᦻ16.this,context=createWebApplicationContext(servletContext,parent);17.servletContext.setAttribute(18.WebApplicationContext.R00T_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this,context);19.........................20.21.returnthis,contextO22.}23.........................24.)

20qt᪷ᦻḄ᱄ᦻrᵨḄ☢ḄHṹ[aᙠweb.xml?Ḅ\ᦪPlocatorFactorySelector,;⌱\ᦪPJavaHṹk1.protectedApplicationContextloadParentContext(ServletContextservletContext)2.throwsBeansException{3.4.App1icationContextparentContext=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.getInstance(locatorFactorySelector);11.......................12.஻ᑮ᪷ᦻḄ᱄ᦻḄᵨ13.this.parentContextRef=locator.useBeanFactory(parentContextKey);14.஻;oqtᑮ᪷ᦻḄ᱄ᦻ15.parentContext=(ApplicationContext)this,parentContextRef.getFactory();16.)17.18.returnparentContext;19.)ᑮ᪷PᦻḄ᱄ᦻ!᪷ᦻḄpqPJavaHṹ!J1.protectedWebApplicationContextcreateWebApplicationContext(2.ServletContextservletContext,ApplicationContextparent)throwsBeansException{3.஻;o◤⌕?ᡃᐭḄ᪷WebApplicationḄKᵫᙠweb.xml#$Ḅcontextclass#$Ḅ\ᦪ?ᡃ◤⌕ᐭ᪵ḄApplicationContext,4.஻᝞z¢ᨵrᵨ£¤Ḅ஺5.ClasscontextClass=determineContextClass(servletContext);

216.7.஻;oᦻḄpq8.ConfigurableWebApplicationContextwac=9.(Configurab1eWebApp1icationContext)BeanUtils.instantiateClass(contextclass);10.஻;o¥ᢝ^᱄ᦻ3ServletContextḄᵨᑮ᪷ᦻ11.wac.setParent(parent);12.wac.setServletContext(servletContext);13.14.஻;oweb.xml[§ᐵḄ45ᓄ\ᦪ15.StringconfigLocation=servletContext.getlnitParameter(C0NFIG_L0CATI0N_PARAM);16.if(configLocation!=null){17.wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,18.ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));19.)20.஻;o^WebApp1icationContext_`45ᓄᡃ©ᑮhª៉Ḅrefresh¬ᵨ஺21.wac.refresh();22.returnwac;23.)45ᓄ᪷Applicationcontext!ᐸl®ᑮSevletContext!;᪵qthᐰ°Ḅᐵa᦮ᵨḄᦻ஺;᪷ᦻ±<!ḄDispatcherServlet45ᓄḄZ᎛67ApplicationContextḄ᱄ᦻ஺;ᙠ^DispatcherServlet³ᑖ᪆ḄZ᎛ᡃᑮ஺3./ᡂ^ContextLoaderListenerḄ45ᓄ!Tomcatµ545ᓄDispatchServlet,-¶·ᡃᙠweb.xml¸ᐭ¹@_`h?஺DispatcherServlet±qtḄApplicationContext,Zqt;ḄᦻḄZ᎛±ServletContextᑮ᪷ᦻ67᱄ᦻ,ᯠ!»^Ḅᦻ_`45ᓄ.ᨬ!lᑮServletContext½!¾¿3rᵨ஺DispatchServletḄ᱄KFrameworkServletḄHṹᑮᜧÁḄ45ᓄ᦮ApplicationContextḄpq3ContextLoderpqḄ§KÂPJavaHṹ1.protectedfinalvoidinitServletBean()throwsServletException,BeansException{2.................3.try{

224.஻;o^ᦻḄ45ᓄ஺5.this.webApplicationContext=initWebApp1icationContext();6.஻ᙠ/ᡂ^ᦻḄ45ᓄÃÄ!᪷bean#$ÅÆqtMVC᪾ÈḄᔜÉ⌕ᐗË7.initFrameworkServlet();8.)9........10.)^initWebApplicationContext()¬ᵨḄHṹ᝞:JavaHṹIJ1.protectedWebApplicationContextinitWebApplicationContext()throwsBeansException{2.஻;o¬ᵨWebApplicationContextUtiIs☟᝱Kᩭᑮ᪷ᦻ3.WebApplicationContextparent=WebApplicationContextUtils.getWebApplicationContext(getServletContext());4.5.஻pq:~DispatcherServletḄᦻᐸᦻÍKrᵨ£¤ḄᙠFrameworkServlet?%ḄPDEFAULT_CONTEXT_CLASS=XmlWebApplicationContext.class;6.WebApplicationContextwac=createWebApp1icationContext(parent);8.if(isPublishContext()){9.஻:~qtḄᦻlᑮServletContextrᵨḄ(ឋÎ3:~ServletΧᐵḄ஺10.StringattrName=getServletContextAttributeName();11.getServletContext().setAttribute(attrName,wac)B12.)13.returnwac;14.)ᐸᡃᑮ¬ᵨhWebApplicationContextUtiIsḄ☟᝱Nᑮ᪷ApplicationContext:JavaHṹT'J1.publicstaticWebApplicationContextgetWebApp1icationContext(ServletContextsc){

232.஻éêᓫServletContexts(ឋÎᑮ᪷ᦻ3.Objectattr=sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);4.......5.return(WebApp1icationContext)attr;6.)7.ᯠ!pqDispatcherServletḄWebApplicationContext:8.protectedWebApplicationContextcreateWebApplicationContext(WebApplicationContextparent)9.throwsBeansException{10.11.஻!"#ᵨ%BeanUtils'()ᑮWebApplicationContext,ContextClass,-☢/01ḄDEFAULTCONTEXTCLASS=7712.//XmlWebApplicationContext.class;13.Configurab1eWebApplicationContextwac=14.(ConfigurableWebApplicationContext)BeanUtils.instantiateClass(getContextClass());15.16.஻!"NO᱄FGᦻKQ,ᙠContextLoaderSTUḄ᪷FGᦻ17.wac.setParent(parent);18.19.஻WᶇServletContextḄZᵨ[\ᐵḄNO^KLஹo20.wac.setServletContext(getServletContext());21.wac.setServletConfig(getServletConfig());22.wac.setNamespace(getNamespace());23.24.஻!")ᑮApplicationcontextNOᦻ_Ḅ`O25.if(getContextConfigLocationO!=null){26.wac.setConfigLocations(27.StringUtils.tokenizeToStringArray(28.getContextConfigLocationO,Configurab1eWebApp1icationContext.C0NFIG_LOCATION_DELIMITERS));29.)30.

2431.஻!"jᵨApplicationcontextḄklᓄnoKp᪵◤⌕#ᵨrefresh()32.wac.refresh();33.returnwac;34.)4.ᯠuQ,DispatchServletSvSpringMVCḄNOnoK✌ᐜvNOᦻ_SḄ/0ᐗ{|}NO-!᎛ᡃḄWebApplicationContextTUᩭ%KᕡḼDispatcherServletᨵḄ/0K◤⌕web.xmlSbeanḄNO^LKᡃ#ᵨᓫḄxmlᦻ_ᩭNOMVCSᔜ⌕{/0K!"[webᘤ\ᐵḄ¡no¢▭F¤ᡂ%KG☢Ḅᜐᳮ[¨ḄSpring©ᵨoªḄ«ᑏᨵ®¯°ᜧḄ²³Kᡃᐜ´´MVCḄklᓄno:Java·ṹp1.protectedvoidinitFrameworkServlet()throwsServletException,BeansException{2.initMultipartReso1ver();3.initLocaleResolver();4.initThemeResolver();5.initHandlerMappings();6.initHandlerAdapters();7.initHandlerExceptionResolvers();8.initRequestToViewNameTranslator()9.initViewResolvers();10.)5.!᪵MVCḄ᪾¼QTUᩭ%KDispatchServletv(½ᑮḄHTTPRequest|}ᑖ¿ᜐᳮᵫdoService஺¤ᡂKᐹÃḄMVCᜐᳮnoᡃᙠdoDispatchOS¤ᡂKᐸSᒹÆ#ᵨCommandÇÈTU᡻}ÊKËÌÇÍᦪÏÐK!ÑᜐᳮᡃÒᙠDispatcherServletḄ·ṹS´ᑮÓJava·ṹ1.protectedvoiddoService(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2...............3.try{4.doDispatch(request,response);5.)6..............7.)¢▭ḄÔᑖ¿ᵫdoDispatch(request,response)ᩭ¤ᡂ:

25Java·ṹ!J1.protectedvoiddoDispatch(finalHttpServletRequestrequest,HttpServletResponseresponse)throwsException{2.................3.//!,Spring/0Ḅ᡻}ÊK"☢Õ%᧜×ᐵØvÙḄhandler[/0Ḅ\ᐵÚÛᘤ஺4.HandlerExecutionChainmappedHandler=null;5.6..................7.try{8.஻ᡃÜ៉ḄModelAndViewᙠ!"Þß%஺9.ModelAndViewmv=null;10.try{11.processedRequest=checkMultipart(request);12.13.஻!"àᐹrequestSḄáᦪ[᧜×ᐵØ/0â/#ᵨḄhandler14.mappedHandler=getHandler(processedRequest,false);15.16.................................17.஻!",handlerḄjᵨnoKãäåCommandÇÈSḄexecute.18.HandlerAdapterha=getHandlerAdapter(mappedHandler.getHandler());19.mv=ha.handle(processedRequest,response,mappedHandler.getHandler());20.21..................................22.஻!"æÇÍᦪÏnçè|}éß23.if(mv!=null&&!mv.wasClearedO){24.render(mv,processedRequest,response);25.)26...............................27.}!᪵ᐹÃḄMVCÇÍḄ¢ßQᵫbeanNOᦻ_"/01Ḅviewresolver,handler!Ñãᩭ¢ßᵨᡝ·ṹḄíî஺ïðF☢ḄnoKᡃ´ᑮᙠwebᘤSKServletContextᢝᨵ7ØᑡḄ

26webFGᦻKóᙠ᦮webFGᦻSõᙠ7᪷FGᦻᩭö÷ᐸøServletFGᦻḄ᱄FGᦻ஺!᪷FGᦻ,ᵫContextLoader¡ᐭú|}klᓄḄKvåᡃḄwebÙᵨKDispatcherSerlvet¡ᐭúklᓄḄFGᦻ,!FGᦻḄ᱄FGᦻ,᪷FGᦻKúûᡃîServletContextS᪷ÏServletḄüýᩭþÿᑮᡃ◤⌕ḄServletḄᦻ᪷ᦻḄᵫSpring!"Ḅ஺DispactcherServlet)*Ḅᦻ+ᡃ,-SpringMVCᵨḄI0C5ᘤ஺ᐹ8Ḅweb;<ᜐᳮᙠᦻ8@)*AᡂCDᵫDispactcherServletᩭAᡂ,☢MVCḄHIJKᜧMḄNO☢ᡃPᐹ8+SpringMVCḄ᪾RSTIUVḄᑖ᪆஺===============================3==================================SpringYZṹ\᪆(^.)aSpringJDBC☢ᡃbbSpringJDBCeᐵḄSTᙠSpringgJdbcTemplateklmnᵨḄoᩭpqᵨᡝstuIᦪwxᙠJdbcTemplateyᵨᡝstz{K|}~ᑭḄᦪwxuI᝞ᙠSpringgᨵ|}oJdbcTemplateḄ᝞HibernateTemplate-bᩭRod.JohnsonḄᵨTemplategᦪCallBackoḄnᵨᩭAᡂḄ¡ᡝ◤⌕ᙠ¢£gST¤¥◤⌕Ḅ"ᑴ§y᝞nᵨ¡ᡝ¨⌕ᵨḄSQL«¬஺®®SpringᦪḄST¯kyᡃz{K|}TᡂḄ{¡ᡝnᵨ஺ᩭ°ᦪḄᵨ±ᵨ²oḄ³ᩭST᝞aJavaZṹṹ1.JdbcTemplate=newJdbcTemplate(datasource);2.JdbcTemplate.execute(newCallBackO(3.publicCallbacklnterfacedoInAction(){4....................................5.஻ᵨᡝ"ÂḄZṹᡈὅ°SpringÅᡃSTḄZṹ6.)7.)ᙠgÈᐭḄ◤⌕¡ᡝᓄḄZṹᵫSpringᩭIᡈὅ◤⌕¡ᡝstˤÌAᡂ஺☢Íᡃᐹ8bbᙠJdbcTemplategḄZṹÎ᪵AᡂnÐḄᡃÑJdbcTemplate.execute஺yÒᙠJdbcTemplategmᐸÔᵨḄÕÖסᡝst®®ᵨᩭ᡻§ÕÖḄSQL«¬aJavaZṹTj1.publicObjectexecute(ConnectionCallbackaction)throwsDataAccessException(2.஻ÛÜᑮᦪwxὶ¢3.Connectioncon=DataSourcelltiIs.getConnection(getDataSource());

274.try{5.ConnectionconToUse=con;6.஻ᨵàᱯâḄᦪwx◤⌕ᡃnᵨᱯãḄäÜdatasource7.if(this.nativeJdbcExtractor!=null){8.//ExtractnativeJDBCConnection,castabletoOrac1eConnectionorthelike.9.conToUse=this.nativeJdbcExtractor.getNativeConnection(con);10.)11.else{12.//Createclose-suppressingConnectionproxy,alsopreparingreturnedStatements.13.conToUse=createConnectionProxy(con)14.}15.஻ÛᵨḄì⌴îᩭḄ²oḄï+ᵨᡝst◤⌕STCallBack¢£Ḅᙢ஺16.returnaction.doInConnection(conToUse);17.)18.catch(SQLExceptionex){19.஻᝞ñᣓᣍᑮᦪwxôlõᦪwxὶ¢ö÷øùúûkSpringüᣚḄSpringᦪwxôl20.஻ᡃþ⍝SpringᨵḄᦪᑮḄ஺21.DataSourceUtils.releaseConnection(con,getDataSource());22.con=null;23.throwgetExceptionTranslator().translate(zConnectionCallbackzz,getSql(action),ex);24.)25.finally{26.஻ᨬHIJK᪵MNᦪOPQR27.DataSourceUtils.releaseConnection(con,getDataSource());28.)29.)VWJdbcTemplate[\]Ḅᐸ_`ab᝞query,update,executedḄef,ᡃhiiquery()jJavalṹ!J

281.publicObjectquery(PreparedStatementCreatorpsc,finalPreparedStatementSetterpss,finalResultSetExtractorrse)2.throwsDataAccessException{3...........4.஻sᵨᡃhu☢iᑮḄexecute஺wx`aᯠzḄ{sefSpring|ᡃh}ᡂḄ5.returnexecute(psc,newPreparedStatementCalIback()6.publicObjectdoInPreparedStatement(PreparedStatementps)throwsSQLException{7.஻ᜓ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(rsToUse)22.)23.finally{24.஻ᨬHᐵ¢Ḅ£VᦪOPḄQRᙠexecute()[QRᡃhᙠu☢ᑖ᪆Ḅiᑮ᪵஺25.JdbcUtils.closeResultSet(rs);26.if(pssinstanceofParameterDisposer){27.((ParameterDisposer)pss).cleanupParameters();28.)29.)30.)31.});32.)

29¥¦§DataSourceUtilsᩭᵨᩭVᦪOP©JᳮḄ«⌕ᐹb᝞ᡭ®¯ᐵ¢ᦪᢞPdwx±jJavalṹz1.publicstaticConnectiondoGetConnection(DataSourcedataSource)throwsSQLException{2.஻VᦪOPRᑮ³´Jᳮ☢©Jᳮ3.ConnectionHolderconHolder=(ConnectionHo1der)TransactionSynchronizationManager.getResource(dataSource);4.if(conHolder!=null&&(conHolder.hasConnection()I|conHolder.isSynchronizedWithTransaction())){5.conHolder.requested();6.if(!conHolder.hasConnection()){7.logger,debug("FetchingresumedJDBCConnectionfromDataSource");8.conHolder.setConnection(dataSource.getConnection());9.}10.returnconHolder.getConnectionO;11.)12.//¾ᑮ◤⌕ḄᦪOP,ᙠᦻÀ[ÁÂḄ஺13.logger,debug("'FetchingJDBCConnectionfromDataSource);14.Connectioncon=dataSource.getConnectionO15.16.if(TransactionSynchronizationManager.isSynchronizatio□Active()){17.logger,debug("RegisteringtransactionsynchronizationforJDBCConnection");18.//UsesameConnectionforfurtherJDBCactionswithinthetransaction.19.//Thread-boundobjectwillgetremovedbysynchronizationattransactioncompletion.20.ConnectionHo1derholderToUse=conHolder;21.if(holderToUse==null){22.holderToUse=newConnectionHolder(con);23.)24.else{25.holderToUse.setConnection(con);26.}27.holderToUse.requested();

3028.TransactionSynchronizationManager.registerSynchronization(29.newConnectionsynchronization(holderToUse,dataSource));30.holderToUse.setSynchronizedWithTransaction(true)31.if(holderToUse!=conHolder){32.TransactionSynchronizationManager.bindResource(dataSource,holderToUse);33.)34.)35.36.returncon;37.)ᡃhe▭ḄDataSourceVÇK᪵¾ᑮḄÈÉÊËᡃh◤⌕ᙠuÌᦻ[©jÍ|JdbcTemplate᱄§JdbcAccessorḄÏឋÑᙠjJavalṹI'J1.publicabstractclassJdbcAccessorimplementsInitializing•Bean\2.3./**ᡃhÕÖ×ᐭᦪᦪÙḄᙢ`஺*/4.privateDataSourcedataSource;5.6./**HelpertotranslateSQLexceptionstoDataAccessExceptions*/7.privateSQLExceptionTranslatorexceptionTranslator;8.9.privatebooleanlazylnit=true;10.11.12.)zVWDataSourceḄÛÜÝefᡃhÞÁApacheJakartaCommonsDBCPᡈὅC3PoáâḄDataSourceᩭ}ᡂᯠHã⌕ᙠuÌᦻ[Âäåæᵨ஺çu☢ᡃhiᑮJdbcTemplateáâèéêᓫ¯ìíîïð᝞◤⌕ìñòóḄôÇåõì☢ᔣVÇḄ`aᩭ÷øᦪ஺Spring|ᡃháâorg.springframework,jdbc.objectᒹ☢ᒹúSqlQuery,SqlMappingQuery,SqlUpdate¯StoredProcedured§§MSpringJDBCûᵨüäåæᵨḄ«⌕§ðᡃh⌕×æᵨ§Ḅý᎛ᵨᡝ◤⌕JdbcTemplateᐸḄḄ஺

31᝞!ᡃ#ᵨMappingSqlQueryᩭ0⊤ᦪ345᧜7ᑮ9:;ᔠ-ᐹ?@ABὃDEḄFG1.ᡃ◤⌕JKDataSourceNsqlPQRJKᢝᨵUV9:ḄMappingSqlQuery9:2.ᯠYᡃ◤⌕Z[\⌴ḄSqlParameter,ᐹ?ḄᡃᙠMappingSqlQueryḄ᱄bRdbmsOperationE@AeᑮfJavahṹ1.publicvoiddeclareParameter(SqlParameterparam)throwsInvalidDataAccessApiUsageException{2.஻᝞uvwxyz{|}~ᑣvwᦔ3.if(isCompiledO){4.thrownewInvalidDataAccessApiUsageExceptionC'Cannotaddparametersoncequeryiscompiled");5.}6.஻U9BᦪvwZ[7.this.declaredParameters.add(param);UdeclareParametersḄᑡ⊤fJavahṹ?J1./**ListofSqlParameterobjects*/2.privateListdeclaredParameters=newLinkedList();Uᑡ⊤ᙠAYcompileḄ}Ez#ᵨ஺3.ᯠYᵨᡝ¡◤⌕MappingSqlQueryḄmapRow5¢~0ᐹ?ḄResultSetᦪ3£ᡂᡃ◤⌕Ḅ9:~Uᡃ¥h#ᵨḄ¦§஺1,2,3¨▭ªᡃZ[«¥hḄᓫᐗ®¯஺4.ᙠ°ᵨ¡~ᡃ45±ᵨexecute஺¦§²ᑮᡃ◤⌕Ḅ9:ᑡ⊤~ᑡ⊤EḄ³9:Ḅᦪ3ᩭ´µ᡻SQLPQ²ᑮ·¸;Ḅ³ᩩ·¸~ºª᡻Ḅexecuteᙠ᱄bSqlQueryE»ᵨfJavahṹ1.publicListexecuteByNamedParam(MapparamMap,Mapcontext)throwsDataAccessException{2.validateNamedParameters(paramMap);3.Object[]parameters=NamedParameterUtils.buildValueArray(getSql(),paramMap);4.RowMapperrowMapper=newRowMapper(parameters,context);5.StringsqlToUse=NamedParameterUtils.substituteNamedParameters(getSql(),newMapSqlParameterSource(paramMap));

326.஻ᡃÁÂᑮ«JdbcTemplate,U#ᵨJdbcTemplateᩭÃᡂ9ᦪ3ÄḄÅÆ~ᡠAᡃ!JdbcTemplateḄb஺7.returngetJdbcTemplate().query(newPreparedStatementCreator(sqlTolIse,parameters),rowMapper);8.)ᙠUᡃ@AÂᑮtemplate®ÉḄÊË°ᵨN9JdbcTemplateḄᮣÍ#ᵨ஺Î}#ᵨÏ~ᡃÐÑ«ÒÓ¥hResultSetR0ᐸEḄᦪ3Ôᓄ9:ᑡ⊤ḄÖ×}஺ᙠUᡃØ◤⌕Z[SQLPQNSqlParameter-᝞u◤⌕ḄÙ~ÚÚSQLPQÛÜÜÝÞßàᡃḄ⌕á«஺UᮣÍ#ᵨJdbcTemplateḄâḄFG஺Springãᐸᦪ3Ääå«æçèé~᝞#ᵨSqlUpdateêᐭNìíᦪ3Ä~#ᵨUpdatableSqlQueîìíResultSet,£ᡂïð~±ᵨñò}ó஺DEãôõ«9BLOBᦪ3NCL0Bᦪ3ᦪ3ÄḄFGf9BLOBᦪ3ḄÎ}LobHanderᩭÃᡂ~Î}±ᵨJdbcTemplateNRDBMSø@AfᙠJdbcTemplateE~ᐹ?Ḅ±ᵨ@ABὃDEḄFG-Î}Aù±ᵨ»ᵨḄfJavaṹú1.publicObjectexecute(Stringsql,PreparedStatementCalIbackaction)throwsDataAccessException{2.returnexecute(newSimplePreparedStatementCreator(sql),action);3.)ᯠYÎ}9PreparedStatementCalIback5¢ḄAbstractLobCreatingPreparedStatementCalIbackḄû±üᦪᩭÃᡂfJavahṹᔣ1.publicfinalObjectdoInPreparedStatement(PreparedStatementps)throwsSQLException,DataAccessException{2.LobCreatorlobCreator=this.lobHandler.getLobCreator();3.try(4.஻U®¯¦§~ᐹ?◤⌕ᵫÿᡝ5.setValues(ps,lobCreator);6.returnnewInteger(ps.executeUpdate());7.)8.finally{9.lobCreator.close();10.)11.)

3312.஻,-Ḅ◤⌕1ᡝḄ23ᦪ13.protectedabstractvoidsetValues(PreparedStatementps,LobCreatorlobCreator)14.throwsSQLException,DataAccessException;AᡃCDEᑮsetValues()GHI◤⌕ḄJKLMNOᵨQRsetValuesᩭ,-TUḄVW-ᙠsetValuesZ[ᵨlobCreator.setBlobAsBinaryStremO□_ᡃC``ᐹbḄBLOBVWᙠLobCreatorGc᪵eᡂḄNᡃCHghᵨDefaultLobCreatorWiBLOBVWḄjklJavanṹᔣ1.publicvoidsetBlobAsBinaryStream(2.PreparedStatementps,intparamindex,InputStreambinaryStream,intcontentLength)3.throwsSQLException{4.஻QRJDBCᩭeᡂqBLOBᦪrḄVWNqOracle,SpringstuOrac1eLobHand1erᩭwᢝBLOBVW஺5.ps.setBinaryStream(paramindex,binaryStream,contentLength);6................7.)z☢sᑮḄG||}}ḄSpringJDBChᵨḄ~N`ᑮhᵨSpringJDBCᡃCeᡂᦪrḄVW஺SpringqᦪrVWᨬḄGQRJdbcTeamplateᵨḄ[3ᦪᩭḄNᙠzNstuRMDBḄVWᩭᡃCᑭḄqᦪrḄᦪrVW-DEᨵᐭᔣHibernate᪵Ḅ0/RLᫀ஺q£0/RLᫀḄwᢝNSpringᵫᐸᒹᩭeᡂ஺§Z¨sᑮᐵªexecuteupdateLM«Ḅ¬NupdateLM®ḄG¯°±Ḅ²³ᦪ´ḄHIµᦪN¶·᝞¹ºᐭ»ᦪḄ¼NhᵨḄGjava.sql.PreparedStatement,AexecuteLM¿Ghᵨjava.sql.Statement,ÀÁ¯»ᦪNA·À®¯°±²³ḄµᦪN〉ᔠªÄÅÆÇ⊤ḄÉÊNAupdateLM〉ᔠªËᐭNÌᑤ◀VWNÏGᡃCᙠhᵨÐ◤⌕DEḄ஺==================================4===============================SpringÒnṹÓ᪆ÕÖlSpringMVC×☢ᡃCqSpringMVC᪾Ùnṹᑖ᪆NqªwebApplicationContextḄÛᐵᑖ᪆»ÜÝḄᦻ᫏NᡃCḼáᑖ᪆SpringWebMVC᪾ÙḄ.ᡃCãᑖ᪆DispatcherServletᐭälJavaṹ1m

341.஻GqDispatcherServletḄåæᓄLMN᪷réêᡃCëL☢Ḅ`ᑮqᔜISpringMVCí⌕ᐗïḄåæᓄ2.protectedvoidinitFrameworkServlet()throwsServletException,BeansException{3.initMultipartResolver();4.initLocaleResolver();5.initThemeResolver();6.initHandlerMappings();7.initHandlerAdapters();8.initHandlerExceptionResolvers();9.initRequestToViewNameTranslator();10.initViewResolvers();11.)`ᑮDÓᡃCó⍝NGDispatcherSerlvetḄåæᓄRNõGᙠWebApp1icationContextö÷øᙠḄùú×ḄNÏûEᕡḼᙠåæᓄõḄÐ᎛NI0Cþᘤᡃᙠweb.xmlSpringḄ᎛◤⌕$DispatcherServletḄload-on-startupḄ0ឋ22Ḅ45஺78ᐹ:Ḅ;<ᓄ>?@A᧕ᳮDᡃEinitHand1erMappings()ᩭLL:JavaOṹ!J1.privatevoidinitHandlerMappings()throwsBeansException{2.if(this.detectAHHandlerMappings){3.//YZᑮᡠᨵᙠ^_ᦻabḄHand1erMapping,d$e᣸g4.//52ᙠdij^_ᦻklᨵmnijhandlerMapping,ᡠlᡃ$eopᐭᑮijrYstuvwxᳮ5.MapmatchingBeans=BeanFactoryUtils.beansOfTypelncludingAncestors(6.getWebApplicationContext(),HandlerMapping.class,true,false);7.if(!matchingBeans.isEmptyO){8.this.hand1erMappings=newArrayList(matchingBeans.values());9.//Y>order0ឋᩭ7hand1erMappingᩭᙠlist᣸g10.Collections,sort(this,hand1erMappings,newOrderComparator());11.)12.13.else{

3514.try{15.Objecthm=getWebApplicationContext().getBean(HANDLER_MAPPING_BEAN_NAME,HandlerMapping.class);16.this.handlerMappings=Collections,singletonList(hm);17.)18.catch(NoSuchBeanDefinitionExceptionex){19.//Ignore,we'11addadefaultHandlerMappinglater.20.)21.}22.23.஻᝞ᙠ^_ᦻᨵabḄᡃᵨḄBeanNameUrlHandlerMapping24.if(this.handlerMappings==null){25.this.handlerMappings=getDefaultStrategies(HandlerMapping.class);26........27.)28.)᪵^_ᦻ᛻klᡃ☢Ḅ7IOCAᘤᙠweb᛻pḄᑖ᪆஺DispatcherServlet$abḄᡠᨵHandlerMappingop£ᙠijListY¤l¥stᵨjrḄ¦ijᐗ¨oijHandlerMappingḄ©iª¦ijHandlerMappingklᢝᨵi¬ᑡ®URL¯°ᑮSpringControllerḄ᧜²,³᝞SimpleUrlHandlerMaaping´abijmapᩭᢝᨵi¬ᑡḄ᧜²ᐵ¬஺DisptcherServlet>HandlerMappingWebᵨ?g¶aij᡻t¸¹´ºᡃᙠHanderMappingLᑮḄ᪵HandlerMapping»ij¼½¾JavaOṹ!J1.publicinterfaceHandlerMapping{2.publicstaticfinalStringPATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE=3.Conventions.getQualifiedAttributeName(HandlerMapping.class,SzpathWithinHand1erMapping஻)¿4.஻À▭^uvijHandlerExecutionChain,ᐺÃḄCommandḄÄÅḄᵨj᡻trY☢uvhandlerwÆÇᘤ5.HandlerExecutionChaingetHandler(HttpServletRequestrequest)throwsException;

366.)eḄᐹ:ÀÈ»◤⌕ÀÈijɽÊË©jɽÊËÌÍḄijHandlerExecutionChain,À▭^´ij᡻tr´ºᙠCommandÄÅÎÏḄ᪵jÐ@Ñᓫ´ijᢝᨵijInterceptorrwijController¾JavaOṹ1.publicclassHandlerExecutionChain{2.3.privateObjecthandler;4.5.privateHandlerinterceptor[]interceptors;6.7................8.)©×HandlerwInterceptor◤⌕ᡃabHandlerMappingḄ᎛س᝞7ᐹ:ḄSimpleURLHandlerMapping,e⌕ÚḄ´᪷ÜURL᧜²ḄÊÅÝÞHandlerwInterceptor,ßàuvij£᧜᧜²ḄhandlerMap,á◤⌕ᓛHttp¯°Ḅ᎛◤⌕ᵨj⊤YḄäåᩭᑮ᡻tr஺jÝÞḄ>?ᙠI0CAᘤ;<ᓄSimpleUrlHandlerMappingḄ᎛´æçᡂ᪵l¥ḄD᪆éklᵨᑮmapYḄ᧜²äåYḄäåwbeanᦻêḄäåëìḄ_☢ᐹ:ḄÝÞ>?¾JavaOṹí1.protectedvoidregisterHandlers(MapurlMap)throwsBeansException{2.if(urlMap.isEmpty()){3.logger,warn(^Neither'urlMap'nor'mappings'setonSimpleUrlHandlerMapping");4.)5.else{6.஻YòOᙠSimp1eUr1Hand1erMappingabḄᡠᨵ᧜²ᐗ¨7.Iteratorit=urlMap.keySet0.iterator();8.while(it.hasNext0){9.஻YôḄurl10.Stringurl=(String)it.next();11.஻Y᪷Üurlᙠbeanabô7Ḅhandler

3712.Objecthandler=urlMap.get(url);13.//Prependwithslashifnotalreadypresent.14.if(!url.startsWith(஻/஻)){15.url=஻/஻+url;16.}17.஻YøᵨAbstractHandlerMappingḄÝÞ>?18.registerHandler(url,handler);19.)20.}21.}ᙠAbstractMappingHandlerḄÝÞOṹ:JavaOṹ¾J1.protectedvoidregisterHandler(StringurlPath,Objecthandler)throwsBeansException,IllegalStateException{2.஻ùú®handlerMapôhandler,LLᔲüᙠd᪵ḄUri᧜²ᐵ¬3.ObjectmappedHandler=this.handlerMap.get(urlPath);4.if(mappedHandler!=null){5................6.)7.8.஻᝞ýÉᵨbeanþÚ᧜²´ýÉ®Aᘤôhandler9.if(!this.lazylnitHandlers&&handlerinstanceofString){10.StringhandlerName=(String)handler;11.if(getApplicationContext0.isSingleton(handlerName)){12.handler=getApplicationContext().getBean(handlerName);13.}14.)15.஻ᡈὅ*ᵨ,-Ḅhandler.16.if(urlPath.equals(஻/*஻)){17.setDefaultHandler(handler);18.)19.else{

3820.஻9url:handlerḄ;<ᐵ>?ᑮhandlerMapBC21.this.handlerMap.put(urlPath,handler);22...................23.)24.}handlerMapEᢝᨵḄHIHashMap,J☢LMNOᐹQḄ᧜STU:JavaYṹ1.privatefinalMaphandlerMap=newHashMap();\Simp1eUr1Hand1erMapping;^_HandlerMappingḄ`aEb᪵ḄdbIgetHandler᪷fᙠhiᓄḄk᎛LmᑮḄ᧜S⊤ᩭpᡂDispatcherServlet◤⌕Ḅ᡻uvHJavaYṹwx1.publicfinalHandlerExecutionChaingetHandler(HttpServletRequestrequest)throwsException{2.஻bJ᪷frequestBḄ|ᦪmᑮᐸ;<Ḅhandler,ᐹQᜐᳮᙠAbstractUr1Hand1erMappingB3.Objecthandler=getHandlerlnternal(request);4.஻᝞ᑮ;<ḄdL*ᵨḕḄhandler5.if(handler==null){6.handler=this.defaultHandler;7.)8.஻᝞ḕḄᨵdLO9.if(handler==null){10.returnnull;11.)12.//᝞handlerEHIᐹQḄhandler,ᡃ⌕ᑮᦻB13.if(handlerinstanceofString){14.StringhandlerName=(String)handler;15.handler=getApplicationContext().getBean(handlerName);16.)17.஻pᡂHIHandlerExecutionChain,ᐸB?OᡃᓛḄhandler:ḄᘤdLᡃᙠHandlerExecutionChainBᑮḄ᪵dᢝᨵHIhandler:HIᘤ஺18.returnnewHandlerExecutionChain(handler,this,adaptedlnterceptors);19.)

39ᡃEQḄhandler¢£¤¥JavaYṹIJ1.protectedObjectgetHandlerInternal(HttpServletRequestrequest)throwsException{2.஻bJḄHTTPRequest¦§ᩭḄ|ᦪ§uᑖ᪆dmᑮᐹQḄª«TU஺3.StringlookupPath=this.urlPathHelper.getLookupPathForRequest(request);4...............஻☢E᪷f¬TUḄ¢5.returnlookupHandler(lookupPath,request);6.)7.8.protectedObjectlookupHandler(StringurlPath,HttpServletRequestrequest){9.//᝞®¯°^®ᙠSimp1eUr1Hand1erMappingḄ᧜S⊤Bᑮdᨬ஺10.Objecthandler=this.handlerMap.get(urlPath);11.if(handler==null){12.//bJ*ᵨ²³ᩭ;mapBḄᡠᨵhandler§uᓛdµᵨOJreBḄMatcher¶ᩭ·ᡂᓛᜐᳮ஺13.StringbestPathMatch=null;14.for(Iteratorit=this.handlerMap.keySet().iterator();it.hasNext0;){15.StringregisteredPath=(String)itTnext();16.if(this.pathMatcher.match(registered?ath,urlPath)&&17.(bestPathMatch==nullI|bestPathMatch.length()<=registeredPath.length())){18.஻bJ᪷fᓛª«ᑮᨬ¸ḄHI19.handler=this.handlerMap.get(registeredPath);20.bestPathMatch=registeredPath;21.)22.)23.24.if(handler!=null){

4025.exposePathWithinMapping(this.pathMatcher.extractPathWithinPattern(bestPathMatch,urlPath),request);26.)27.)28.else{29.exposePathWithinMapping(urlPath,request);30.)31.//32.returnhandler;33.)ᡃ¹ºᑮd»EᙠhandlerMapbIHashMapBd¼ᯠ᝞°^ᑮᨬd᝞ᑮdLEE®¾£MatchPatternḄ²³dᡃH¿mᙠÀHnaderMappingḄk᎛E¹º¾£ANTÁ§uÀḄdᐸBḄᜐᳮLᙠbJ஺b᪵¹ºÂÃᙢᑮ᦮IHandlerMappingḄhiᓄ£¤-ÇkdᡃᑮOHIᐹQḄhandler᧜SEÈ᪵ÉNÊ:¢Ḅ-bJpᡂHIExecutionChainᩭÊNᡃᑮḄhandler:ᙠbeanḄk᎛ḄInterceptors.ËᡃÌᑮDispatcherServlet,hiᓄ·ᡂºÍd`▭Ḅ;web¬EᙠdoService()ÏBᜐᳮḄdᡃÐ⍝DispatcherServletÒEHIÓ¾ḄServlet:JavaYṹ!-J1.protectedvoiddoService(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2...............3.஻bJ9ÔឋTU§uMN4.MapattributesSnapshot=null;5.if(WebUtils.isIncludeRequest(request)){6.logger.debug(''Takingsnapshotofrequestattributesbeforeinclude");7.attributesSnapshot=newHashMap();8.EnumerationattrNames=request.getAttributeNames();9.while(attrNames.hasMoreElements()){10.StringattrName=(String)attrNames.nextElement();11.if(this.cleanupAfterlnclude||attrName.startsWith(DispatcherServlet.class.getName())){

4112.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.1ocaleResolver);20.request.setAttribute(THEME_RESOLVER_ATTRIBUTE,this.themeResolver);21.request.setAttribute(THEME_SOURCE_ATTRIBUTE,getThemeSource());22.23.try{24.஻bJ*`▭Ḅᜐᳮᐭ_25.doDispatch(request,response);26.)27.finally{28.//Restoretheoriginalattributesnapshotincaseofaninclude.29.if(attributesSnapshot!=null){30.restoreAttributesAfterInclude(request,attributesSnapshot);31.)32.)33.)ᡃᑮd;à¬Ḅᜐᳮ`▭EËdoDispatch()ᩭ·ᡂḄ-bIÏáâdãE£¤áäᓫæO¥JavaYṹI'J1.protectedvoiddoDispatch(finalHttpServletRequestrequest,HttpServletResponseresponse)throwsException{2.HttpServletRequestprocessedRequest=request;3.஻bEèhandlerMappingBmᑮḄ᡻uv4.HandlerExecutionChainmappedHandler=null;5.intinterceptorIndex=-1;6.7.................

428.try(9.஻ᡃé៉ḄModelAndViewëiìaO஺10.ModelAndViewmv=null;11.try(12.processedRequest=checkMultipart(request);13.14.//bEᡃmᑮhandlerḄ£¤15.mappedHandler=getHandler(processedRequest,false);16.if(mappedHandlernull|mappedHandler.getHandler()null){17.noHandlerFound(processedRequest,response);18.return;19.20.21.//bJì᡻uvBḄInterceptor§uíᜐᳮ22.if(mappedHandler.getInterceptors()=null){23.for(inti=0;i

4336.37.//bJì᡻uvBḄInterceptor§uÍᜐᳮ38.if(mappedHandler.getlnterceptors()!=null){39.for(inti=mappedHandler.getlnterceptors().length-1;i>=0;iü){40.HandlerInterceptorinterceptor=mappedHandler.getlnterceptors0[i];41.interceptor.postHandle(processedRequest,response,mappedHandler.getHandler(),mv);42.)43.)44.)45.46.47.48.//Didthehandlerreturnaviewtorender?49.஻bJ;þÿᡂᜐᳮ50.if(mv!=null&&!mv.wasClearedO){51.render(mv,processedRequest,response)52.}53.54.)ᡃ,-./Ḅ1ᑮ3MVC᪾789:ᐵḄ<ṹ>?᝞᝞ABᑮ3httpDE:FGḄ᡻I>J᪵᡻᡻I3J᪵LMNᦪPQRᑮSTUV஺ᐜ1J᪵YBCommandFZ>Fᡃ,ᩭ\]^Handler-a☢^getHandlerḄ<ṹdJava<ṹ!'J1.protectedHandlerExecutionChaingetHandler(HttpServletRequestrequest,booleancache)throwsException{2.஻ᙠServletContextYB᡻I-m▭opqrBᑮsḄt᎛,ᡃ,LsvᙠServletContextwxy஺3.HandlerExecutionChainhandler=4.(HandlerExecutionChain)request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);5.if(handler!=null){

446.if(!cache){7.request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);8.)9.returnhandler;10.)11.஻Ḅ<ᘤ<ḄtᙠinitHandlerMappingUᐭḄoaᦻᡠᨵḄHandlerMapping12.Iteratorit=this.handlerMappings.iterator0;13.while(it.hasNext()){14.HandlerMappinghm=(Hand1erMapping)it.nex10;15.......16.஻^m▭YBhandlerḄ,ᙠHandlerMappingUḄ᧜⊤BᑮDEFGḄhandler17.handler=hm.getHandler(request);18.19.஻ᯠLhandleryᑮServletContextUVxy20.if(handler!=null){21.if(cache){22.request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE,handler);23.}24.returnhandler;25.}26.)27.returnnull;28.}᝞ᙠServletContextUYBhandlerᑣ¡¢>m▭ohandler^x£worᜐᳮḄ¤-¥⌕ᨵpqrLhandlervᑮServletContextUVd᝞ᙠServletContextU§¨ᑮhandler,©]ªᢝᨵḄhandlerMappingᡂq>ᡃ,1ᑮs¬<®ᢝᨵḄᡠᨵḄhandlerMapping,¯°±²¨³q>´,ᙠ±²Ḅt᎛µᢣ±·¸>ᑮ§ᑮpq>ᯠ¡¢஺ᐜ§ᑮqhandlerMapping,ᯠªhandlerMapping¡¢q᡻I>☢ᒹºwᨬ¼ḄHandler3ᡃ,±²Ḅq½¾ḄInterceptor஺ᐹÀḄᡃ,Áὃo☢ḄSimpleUrlHandlerMappingḄ<ṹᑖ᪆Å⍝getHandler^J᪵BᑮqHandlerExecutionChainḄ஺BᑮHandlerExecutionChain>ᡃ,ªHandlerAdapterFHandlerḄᔠÈឋÊᑨÌdJava<ṹA

451.protectedHandlerAdaptergetHandlerAdapter(Objecthandler)throwsServletException{2.Iteratorit=this.handlerAdapters.iterator0;3.while(it.hasNext()){4.஻Í᪵FᢝᨵḄᡠᨵadapterᓛÏ5.HandlerAdapterha=(HandlerAdapter)it.nex10B6.if(ha.supports(handler)){7.returnha;8.)9.)10...............H.)ªᑨÌ>ᡃ,Å⍝handler^¨^qControllerÐḄmR>?᝞FÑᐹÀḄHandlerAdapter-SimpleControllerHandlerAdapter:Java<ṹ!J1.publicclassSimp1eControllerHand1erAdapterimplementsHandlerAdapter{2.3.publicbooleansupports(Objecthandler){4.return(handlerinstanceofController);5.)6...............7.)ÒᓫḄᑨÌqahandler^¨^mRwControllerÐ஺µÀRwqÔFÏÕᦻÖ×ØḄÙᑴ஺Ûᡃ,Ü¢ᑮDispatcherServlet1ᑮ<ṹdJava<ṹ!-J1.mv=ha.handle(processedRequest,response,mappedHandler.getHandler());]^FhandleḄᐹÀÝᵨß:ÑCommandMàḄCommand,execute();ᳮᡠᯠḄ¡¢qModelAndView,a☢]^qFViewᜐᳮḄdJava<ṹ?J1.if(mv!=null&&!mv.wasCleared()){2.render(mv,processedRequest,response);3.)

46ÝᵨḄ^renderáÈ:Java<ṹᑁ1.protectedvoidrender(Mode1AndViewmv,HttpServletRequestrequest,HttpServletResponseresponse)2.throwsException{response.setLocale(locale);3.4.Viewview=null;5.஻LæçḄSTvᑮModelAndViewUV஺6.if(!mv.hasView()){7.mv.setViewName(getDefaultViewName(request));8.)9.10.if(mv.isReferenceO){11.//FSTìíî᪆12.view=resolveViewName(mv.getViewName(),mv.getModelInternal(),locale,request);13.14.)15.else{16.//ᨵïᙠModelAndViewðñᒹºwViewFZ>©ᡃ,]òᵨ஺17.view=mv.getViewO;18.19.)20.21.஻BᑮᐹÀḄViewFZ>ᡃ,ᵨsᩭᡂST஺22.view,render(mv.getModelInternal(),request,response);23.)ó᦮ᡃ,1ᑮᐜᙠModelAndViewUõ§STḄö÷ì>᝞§¨ᑮ©]òᵨøḕḄST>᝞ïú§ᑮSTḄìí>©]F´î᪆Bᑮm▭Ḅ◤⌕òᵨḄSTFZ஺üᨵqÔï]^ᙠModelAndViewUðñᒹºwm▭ḄSTFZ>STFZ^òᵨḄ஺¨ýJ᪵>BᑮqSTFZ>ªÝᵨSTFZḄrenderᩭþᡂᦪPḄÿᡃᐹḄJstlView᪵ḄᡃᙠJstlViewḄ᱄AbstractView#$ᑮrender()*Javaṹᔣ

471.publicvoidrender(Mapmodel,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{2...............3.///01ᡠᨵḄ4ᐵ678ᦈ:ᑮ;

4814.RequestDispatcherrd=request.getRequestDispatcher(dispatcherPath);15.if(rd=null){16.thrownewServletException(17.“CouldnotgetRequestDispatcherfor[஻+getUrl()+஻]:checkthatthisfileexistswithinyourWAR");18.}19.✌ᐜ@AᦪCQRᜐᳮexposeModelAsRequestAttributesᙠAbstractview#Ḅ/<()1ModelAndView#Ḅ@AᦪCᐸYrequestᦪCUᑮServletContext#m/᪵᦮<@AᦪC[ServletContext☄^ᑮᐳ¢£ᵨO*Java\ṹ¤J1.protectedvoidexposeModelAsRequestAttributes(Mapmodel,HttpServletRequestrequest)throwsException{2.Iteratorit=model.entrySet().iterator0;3.while(it.hasNext()){4.Map.Entryentry=(Map.Entry)it.next()5.6.StringmodelName=(String)entry.getKey();7.ObjectmodelValue=entry.getValueO;8.if(modelValue!=null){9.request.setAttribute(modelName,modelValue);10.11.)12.else{13.request.removeAttribute(modelName);14.15.)16.)17.)±ᡃ²ᑮᦪCᜐᳮbᑖḄexposeHelperO;/;<@X()ᐸᙠJstlView#*Java\ṹ!,J

491.publicclassJstlViewextendsInternalResourceView{2.3.privateMessageSourcejst1AwareMessageSource;4.5.6.protectedvoidinitApplicationContext(){7.super.initApplicationContext();8.this.jstlAwareMessageSource=9.JstlUtils.getJstlAwareMessageSource(getServletContext(),getApp1icationContext());10.)11.12.protectedvoidexposeHelpers(HttpServletRequestrequest)throwsException{13.JstlUtils.exposeLocalizationContext(request,this.jstlAwareMessageSource);14.)15.16.)ᙠJstlUtils#ᒹµO¶ᐸY·¸jstlᱯºḄᦪCᜐᳮ»¼஺½L¾¿ᡃᙠᙠÀ0O¿ᕣᕣᡃÂÂÃᡂḄÅMVC#ViewḄrender,¶InternalResourceViewḄrenderÆÇÈᓫÊÃᡂ;

504.StringcontentType=getContentType();5.if(contentType!=null){6.view.setContentType(contentType);7.)8.view.setRequestContextAttribute(getRequestContextAttribute());9.view.setAttributesMap(getAttributesMap());10.returnview;11.)/0ÓᡂViewḄᙢ(ÚᯠZ1ÓᡂḄurlᐸY;Ûview4ᐵḄÜឋZÞ¼ßO஺Ï/

511.protectedViewresolveViewName(StringviewName,Mapmodel,Localelocale,HttpServletRequestrequest)2.throwsException{3.஻ᡃᨵò½ó;

5212.Viewview=(View)this.viewCache.get(cacheKey);13.if(view=null){14.஻᝞LᙠQRMᨵxᑮVWyz({VWḄ|ᑮQR}15.view=createView(viewName,locale);16.this.viewCache.put(cacheKey,view);17........18.)19.returnview;20.}21.}22.)ᐵucreateView(),loadViewO,buildViewOḄᐵᡃEclipsevḄcallhiearchyᯠᡃᑮview.renderᡂᦪḄᨬhttpResponseḄᑏᐭ᝞ᙠAbstractExcelViewḄ,Java:ṹIJ1.protectedfinalvoidrenderMergedOutputModel(2.Mapmodel,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{3.................4.//response.setContentLength(workbook.getBytes().length);5.response.setContentType(getContentType());6.ServletOutputStreamout=response.getOutputStreamO*7.workbook,write(out);8.out.flush();9.)u᪵ᡃ☢Ḅᑖ᪆yᩭ,DispatcherServletᙠ᪆!"#Ḅ᎛᪷⌕¢)ᡂ!"+ᒹ¤ᙠInternalResourceView◤⌕¥ᵨḄurlᐸ§ᔜ©HTTPresponseªᐵḄ«ឋ®ᑏ¯ᢝᙠ)ᡂḄ!"+ᯠ±²/ᵨ!"+ḄrenderᩭᡂᦪḄ³´஺u᦮zSpringWebMVC᪾¸Ḅᜧº»᦮zMVCº»ᵫDispatcherServletᩭ½ᑴ஺MVCḄᐵ¿À»ᒹ¤,ÁTᑮhandlerḄ᧜Ãᐵ᪵᪷Ä¢ÅᦪÆᑮÇḄhandler,ᙠSpringuᵫhandlerMappingÈÀ᡻%ÊᩭᡂḄËᐹḄ᧜Ãᐵᡃᙠbean

53ÌÍᦻÏÌÍ(ᙠHandlerMappingÐᐭÑÒᦻḄ᎛ÓÁTÔ஺ᯠDispatcherServlet/ᵨHandlerMappingᩭÆᑮÇḄ᡻%ÊᨬÈÀ!"ᩭ³1ÕᦪÖᡃ⌕×ØḄ!"+ᙠ᪆!"#Ḅ᎛)ᡂÁTÔḄ஺uÙÚ᪶ÜÝḄHanderMapping,ViewResolver,View,HandlerḄÞßàÙMVCḄáâ஺======================5==============================================Springã:ṹ᪆(ä),SpringAOPåæProxyÒ☢ᡃᩭSpringḄA0PḄyªᐵ:ṹçÆᑮProxyḄèᡃᡃᐜA0PSpringAOPḄyêëᭆí,Advice,ÈîᑴÌᙠï²ðñòçᙠSping§ó⌕ôõSpringö÷øù/ᵨ×ᐭḄú᜜Ḅ%ÚSpringüýḄÈîÝÕᨵ,beforeadvice,AfterReturningAdvice,ThrowAdvice,MethodBeforeAdvice,uSpringAOPÌÍḄ²þÝᐹḄÿ◤⌕ᵨᡝᩭᡂ஺Pointcut:ᑗᐸadvice!"!ᵨ#$%&'()◤⌕*ᐭ,᜜ᜐᳮḄᙢ2Ḅ3ᔠ5᝞78advice9:᪗Ḅ<2=஺SpringpointcutCDEᕡḼ᪗H2=IJ⌱L<2=Mᵨ9pointcut,SpringOPQᐹSḄᑗᩭTᵨᡝUᵨV᝞Wᑣ⊤Z[ᑗJdkRegexpMethodPointcutCbWᑣ⊤Z[c2=defᓛhᐸCbUᵨAbstractJdkRegexpMethodPointcutlḄcMethodMatcher&mḄᩭᡂpointcutnopJavaqṹst1.publicfinalbooleanmatches(Methodmethod,ClasstargetClass){2.஻Cbᑮ2=Ḅᐰd3.Stringpatt=method.getDeclaringClass().getNameO+஻஻+method.getNameO;4.for(inti=0;i

5416.)17.returnfalse;18.)ᙠJDKRegexpMethodPointcutlCbJDKlḄWᑣ⊤Z[ᓛhᩭᡂpointcutḄᨬ¢£¤Javaqṹl-'J1.protectedbooleanmatches(Stringpattern,intpatternindex)(2.Matchermatcher=this.compiledPatterns[patternindex].matcher(pattern);3.returnmatcher,matches();4.}Advisorp©ᡃ«ᡂ,᜜Ḅ¬®(advice),᜜¬*ᐭḄ®(pointcut)J¯ᡃ«◤⌕c°±²«³ᔠ´ᩭ()Cµᘤ-advisor,·!"ᙠ$!ᵨ$Cµ஺AdvisorḄᨵpDefaultPointcutAdvisor²ᨵ¹ºឋadvicepointcutᩭ¼ᡃ«h½advicepointcut஺&Ḽᡃ«(IJCbProxyFactoryBeanᩭh½ᡃ«Ḅqᳮc°2☢f9ᙠProxyFactoryBeanlᨵinterceptorNamesᩭh½Â÷ÄḄCµᘤ-advisor,ÅᯠḄdÇÈÉinterceptNames,Ê▭Ì)Pᡃ«h½advisorḄᙢ2ᐹSḄqᳮCbJDKḄProxyᡈὅCGLIBᩭᡂ஺Ò9ProxyFactoryBean)FactoryBean,ᙠProxyFactoryBeanlᡃ«CbgetObject஺IJÓ&ᑮqᳮc°pJavaqṹ1.publicObjectgetObject()throwsBeansException{2.஻ÕÖᓄCµᘤØ3.initializeAdvisorChain();4.if(isSingletonO){5.஻᪷Û·◤⌕ÜᡂᓫÞḄProxy6.returngetSingletonlnstance();7.)8.else{9.10.஻᪷Û·◤⌕ÜᡂPrototypeßàḄProxy11.returnnewPrototypelnstance();12.)13.)

55ᡃ«ááâãÜᡂᓫÞḄqᳮc°:JavaqṹIJ1.privatesynchronizedObjectgetSingletonlnstance(){2.if(this.singletoninstance==null){3.this.targetSource=freshTargetSource();4.if(this,autodetectinterfaces&&getProxiedlnterfacesO.length==0&&!isProxyTargetClass()){5.//½qᳮc°Ḅ&m6.setinterfaces(ClassUtils.getAHInterfacesForClass(this.targetSource.getTargetClass()));7.)8.//Eagerlyinitializethesharedsingletoninstance.9.super.setFrozen(this.freezeProxy);10.//êEḄ2=ëUᵨProxyFactoryᩭÜᡂᡃ«◤⌕ḄProxy11.this.singletoninstance=getProxy(createAopProxy());12.//Wemustlistentosuperclassadvicechangeeventstorecachethesingleton13.//instanceifnecessary.14.addListener(this);15.)16.returnthis,singletonInstance;17.)18.19.஻UᵨcreateAopProxyäḄAopProxyᩭᑮqᳮc°஺20.protectedObjectgetProxy(AopProxyaopProxy){21.returnaopProxy.getProxy(this.beanClassLoader);22.}ProxyFactoryBeanḄ᱄ß)AdvisedSupport,SpringUᵨAopProxy&m±AOPqᳮḄî᪾ðḄᐸ²ñᑖᑖóôᩭᙠAdvisedSupportlCb᪵Ḅ2[ᩭᑮAopProxy,©ᯠ◤⌕ᑮAopProxyFactoryḄö÷-ø☢ᡃ«áᑮSpring9ᡃ«OPḄᩭö÷ᡃ«2ùḄúJDKᡈὅcgliblᑮᡃ«û⌕Ḅqᳮc⌲pJavaqṹiJ1.protectedsynchronizedAopProxycreateAopProxy(){2.if(!this.isActive){3.activate();4.)

565.returngetAopProxyFactory().createAopProxy(this);6.)ýᙠProxyConfiglcUᵨḄAopProxyFactoryÉQ·pJavaqṹþ1.஻DefaultAopProxyFactory)SpringᵨᩭÜᡂAopProxyḄᙢ22.஻©ᯠQÿᒹJDKCglib஺3.privatetransientAopProxyFactoryaopProxyFactory=newDefaultAopProxyFactory();ᐸ,ᙠDefaultAopProxyFactory,./᪵1ᡂAopProxyḄ:Java5ṹTii1.publicAopProxycreateAopProxy(AdvisedSupportadvisedSupport)throwsAopConfigException{2.஻✌ᐜὃ⇋Iᵨcglibᩭ5ᳮMNOPᯠ᝞STUV᪗MNX.YZḄ[Ḅ\3.if(advisedSupport.isOptimize()|advisedSupport.isProxyTargetClass()4.advisedSupport.getProxiedlnterfaces().length==0){5.஻/bᑨd᝞SXeᙠcglibfOgYhijk஺6.if(IcglibAvailable){7.thrownewAopConfigException(8.“CannotproxytargetclassbecauseCGLIB2isnotavallable."+9.“AddCGLIBtotheclasspathorspecifyproxyinterfaces.zz);10.)11.///bIᵨCglibᩭ1ᡂProxy,᝞StargetX.YZḄḄ\Ovwcglib[xḄAopProxy12.returnCglibProxyFactory.createCglibProxy(advisedSupport);13.}14.else{15.///bIᵨJDKᩭ1ᡂProxy,vwJDK[xḄAopProxy16.returnnewJdkDynamicAopProxy(advisedSupport)17.}18.)

57{.ᡃ}~ᑮᐸ,Ḅ5ᳮMNᵫJDKᡈὅCglibᩭ1ᡂOᡃ}ᑮJdkDynamicAopProxy[Cglib2AopProxyḄ.AopProxyḄYZOᙠJdkDynamicAopProxy,ᡃ}ᑮProxy.᪵1ᡂḄJava5ṹA1.publicObjectgetProxy(ClassLoaderclassLoader){2.if(logger.isDebugEnabled()){3.Classtargetclass=this,advised.getTargetSource().getTargetClass();4.logger,debug(OzCreatingJDKdynamicproxy"+5.(targetclass!=null?”for["+targetClass.getNameO+6.)7.Classproxiedlnterfaces=AopProxyUtils.completeProxiedlnterfaces(this,advised);8.findDefinedEqualsAndHashCodeMethods(proxiedlnterfaces);9.஻/bᡃ}ᵨJDKProxyᩭ1ᡂ◤⌕ḄProxy10.returnProxy.newProxyInstance(classLoader,proxiedlnterfaces,this);11.)/᪵ᵨProxyᒹtargetOProxyFactoryBeanᑮMᐸḄᵨ~Proxy¡OProxyFactoryBeanḄgetObject()ᑮḄ▭£.¤¥Proxy¡Oᡃ}ḄtargetMN¦§¨¡஺MProxyFactoryBean/¥©ᔆbean«¬Oᐸ1iᩭḄMN.¨¡V᪗MNḄ5ᳮMN஺=====================6==========================================Spring®5ṹ¯᪆(±)Spring²³´µᜐᳮᡃ}Spring,Ḅ´µᜐᳮḄ5ṹOIᵨSpring·ᳮ´µᨵ²³¹ºO²³´µᜐᳮAOPḄ»´ᱥ·ᳮ5ṹ½¾☢¨ᩭÀᔣÂᐭᑮĵ5ṹ,OI´µ·ᳮ5ṹĵ5ṹ¯Å஺ᙠ/ᡃ}ÆᔠIoCÈᘤSpirng¦ᨵḄFactoryBeanᩭM´µ·ᳮÊËÌឋÎÏOÐ᝞ÑÒ˾O◞ÔÕÖ×஺ᐸ,ᨬÙᓫḄ~.ÎÏTransactionProxyFactoryBeanᩭ²³´ᱥÛᙠ᦮¥®5ṹᑖ᪆,Oᡃ}ᜧßᑮSpring²³´ᱥ·ᳮᨵ/àá¥âᑖ*Mᙠ£äᦻ,ÎÏḄÌឋḄᜐᳮO/bæçḄ[.TransactionAttributeSourceAdvisor,/.¤¥èᘤOᵨéᩭMÌឋêÊËᜐᳮOÌឋëìíᙠTransactionAttribute,ᩭIᵨO«/îÌឋḄᜐᳮïï.MᑗᐭñḄᜐᳮ.ÆᔠòᩭḄ஺MÌឋḄᜐᳮíᙠ[

58TransactionAttributeSource,óᡂ஺*ôõ´ᱥḄºO/¥º.öᡲøᐹúḄ´ᱥ·ᳮᘤᩭôõḄOûSpringTransactionStatusᩭÑ⌴ýᐵḄëì஺*M´ᱥḄᜐᳮMýᐵëìḄᑨdᩭöᡲøᐹúḄ´ᱥ·ᳮᘤóᡂ஺ᡃ}ä☢ᐹúḄOᙠTransactionFactoryBean,Java5ṹ?J1.publicclassTransactionProxyFactoryBeanextendsAbstractSingletonProxyFactoryBean2.implementsFactoryBean,BeanFactoryAware{3.஻/b.Spring´µᜐᳮ«IᵨḄAOPᘤO,ÿSpringᜐᳮḄṹᩭᢝᜐᳮḄ4.privatefinalTransactioninterceptortransactionlnterceptor=newTransactioninterceptor();5.6.privatePointcutpointcut;7.8.//SpringTransactionManagerᐭUTransactioninterceptor9.publicvoidsetTransactionManager(PlatformTransactionManagertransactionManager){10.this,transactioninterceptor.setTransactionManager(transactionManager);11.)12.13.஻ᙠbean"#ᦻ%&ᑮḄ(ᳮḄ)ឋ+,ᐭᑮTransactioninterceptor14.publicvoidsetTransactionAttributes(PropertiestransactionAttributes){15.this.transactioninterceptor.setTransactionAttributes(transactionAttributes);16.}17.18................-ḕᶍᐸ12345.......19.20.஻67SpringAOPᜐᳮḄAdvisor21.protectedObjectcreateMainlnterceptor(){22.this,transactioninterceptor.afterPropertiesSet()B23.if(this,pointcut!=null){24.஻8ᵨ:;Ḅ<=ᘤ

5925.returnnewDefaultPointcutAdvisor(this.pointcut,this,transactioninterceptor);26.)27.else{28.//8ᵨ?☢ABCḄTransactioninterceptorDEFGᘤHIJ8ᵨTransactionAttributeSourceAdvisor29.returnnewTransactionAttributeSourceAdvisor(this,transactioninterceptor);30.}31.)32.)KLMJ᎛SpringḄTransactioninterceptorOᐭᑮSpringAOPᡂEAdvisorḄ2QᑖᕖTᡃVWᑮᙠTransactionProxyFactoryBeanHX45ᙠI0CYZᓄbeanḄJ᎛O᡻]^Javaṹ!J1.publicvoidafterPropertiesSet(){2...............3.//TransactionProxyFactoryBean▭?8ᵨProxyFactoryaᡂAOPḄbcde஺4.ProxyFactoryproxyFactory=newProxyFactory0;5.6.if(this.preinterceptors!=null){7.for(inti=0;i

6017.18.if(this.postInterceptors!=null){19.for(inti=0;i

613.//Interceptor8ᵨÈÊᩭḄTransactioninterceptor4.஻ÝÞpointcut,AB2XᑁQxHuàÏ☢Ḅṹ5.privateTransactioninterceptortransactioninterceptorr6.7.privatefinalTransactionAttributeSourcePointcutpointcut=newTransactionAttributeSourcePointcut();8.9.........10.஻ABḄPointCutᑁQx11.privateclassTransactionAttributeSourcePointcutextendsStaticMethodMatcherPointcutimplementsSerializable{12.............13.஻45ᓛ"ḄH8ᵨTransactionAttributeSourcex14.publicbooleanmatches(Methodmethod,Classtargetclass){15.TransactionAttributeSourcetas=getTransactionAttributeSource();16.஻8ᵨTransactionAttributeSourceᩭ"#)ឋÊ]ᜐᳮ17.return(tas!=null&&tas.getTransactionAttribute(method,targetclass)!=null);18.}19.ḕᶍequal,hashcode,tostringḄṹ20.}ᡃVWW)ឋâgs᪵O&ᐭḄ^AbstractFallbackTransactionAttributeSourceãäᐹÖḄ)ឋ&ᐭåHᡃVmnᨵkl&ᐭ4HÃ᝞annotationÆæç"#.ᡃVÏ☢WWæç"#Ḅ&ᐭ4HᙠSpringIJ&ᐭḄ)ឋâÊ]èéᜐᳮHg2Xdecoratorê^Javaṹ!'J1.publicfinalTransactionAttributegetTransactionAttribute(Methodmethod,ClasstargetClass){2.஻ᐜì2Ïèéᨵíᨵ(ᳮḄ)ឋ"#H᝞îᨵïèéðñTransactionAttribute3.ObjectcacheKey=getCacheKey(method,targetClass);4.Objectcached=this.cache,get(cacheKey);

625.if(cached!=null){6.if(cached==NULL_TRANSACTION_ATTRIBUTE){7.returnnull;8.)9.else{10.return(TransactionAttribute)cached;11.)12.)13.else{14.//<45Æ·᪗Ḅ+,ᩭö÷èé)ឋ15.TransactionAttributetxAtt=computeTransactionAttribute(method,targetClass);16.஻ñᑮḄèé)ឋéᑮèéHÏømnæçïèéðñ஺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.)úញHbcḄᜐᳮᙠcomputeTransactionAttribute()^JavaṹIJ1.privateTransactionAttributecomputeTransactionAttribute(Methodmethod,ClasstargetClass){2.஻üýgþgpublic453.if(allowPublicMethodsOnly()&&IModifier.isPublic(method.getModifiersO)){4.returnnull;5.)6.7.MethodspecificMethod=AopUtils.getMostSpecificMethod(method,targetClass);8.

639.//Firsttryisthemethodinthetargetclass10.TransactionAttributetxAtt=findTransactionAttribute(findAllAttributes(specificMethod));11.if(txAtt!=null){12.returntxAtt;13.)14.15.//Secondtryisthetransactionattributeonthetargetclass.16.txAtt=findTransactionAttribute(findAllAttributes(specificMethod.getDeclaringClass()));17.if(txAtt!=null){18.returntxAtt;19.)20.21.if(specificMethod!=method){22.//Fallbackistolookattheoriginalmethod.23.txAtt=findTransactionAttribute(findAHAttributes(method));24.if(txAtt!=null){25.returntxAtt;26.)27.//Lastfallbackistheclassoftheoriginalmethod.28.returnfindTransactionAttribute(findAHAttributes(method.getDeclaringClass()));29.)30.returnnull;31.)789:ᑡḄ=>ᡃ@ABC8findTransactionAttribute()C8DᵨfindAllAttribute஺GᑮTransactionAttributeḄIJK᝞MNOḄPnull,QRSTUVWPᡃ@◤⌕Z[ᜐᳮḄUV஺ᙠ_ᡂa◤⌕ḄCbᘤdᑮProxyFactoryefḄgẠiKᡃ@jjᐹlḄjZ[ᜐᳮmṹo᪵qrᵨKᙠTransactioninterceptoresJavamṹ1.publicObjectinvoke(finalMethodinvocationinvocation)throwsThrowable{2.//QxGᑮy᪗IJ

643.Classtargetclass=(invocation.getThisO!=null?invocation.getThis().getClass():null);4.5.஻Qx~᪵ḄC8ᑨPᔲGᑮTransactionAttributeᩭPᔲIUVZ[ᜐᳮKᨵATឋ7K6.஻ᐹlABὃi☢IgetTransactionAttributeḄᑖ᪆K~᪵PC8TransactionAttributeSource7.finalTransactionAttributetxAttr=8.getTransactionAttributeSource().getTransactionAttribute(invocation.getMethod(),targetClass);9.finalStringjoinpointldentification=methodldentification(invocation.getMethod());10.11.஻Qxᑨᡃ@ᵨTransactionManager12.if(txAttr==null||!(getTransactionManager0instanceofCallbackPreferringPlatformTransactionManager)){13.//QxZ[K~aZ[8eGᑮḄ¡¢ᑮTransactioninfoef14.Transactioninfotxlnfo=createTransactionlfNecessary(txAttr,joinpointIdentification);15.ObjectretValnull;16.try(17.retValinvocation,proceed();18.)19.catch(Throwableex){20.//targetinvocationexception21.completeTransactionAfterThrowing(txInfoex);22.throwex;23.)24.finally{25.cleanupTransactioninfo(txlnfo);26.27.commitTransactionAfterReturning(txInfo);28.returnretVal;29.30.31.else32.//ᵨḄPSpring¦ḄP1atformTransactionManager~§¨OD©ªKᡃ@C8ᐸOD¬ᦪ_ᡂZ[ᜐᳮK®¯ᡃ@ᵨ°±Z[ᜐᳮ9᪵஺33.try{

6534.Objectresult=((CalIbackPreferringPlatformTransactionManager)getTransactionManager()).execute(txAttr,35.newTransactionCalIback(){36.publicObjectdoInTransaction(Transactionstatusstatus){37.//~᪵Ḅ◤⌕9²Transactoninfo38.Transactionlnfotxlnfo=prepareTransactionlnfo(txAttr,joinpointldentification,status);39.try{40.returninvocation,proceed();41.)42.......Qxḕf´µᜐᳮ¶Z[¡Ḅ·ᳮmṹ43.});44...........45.)46.)Qx☢¹ºᑮZ[ḄKᡃ@ABᙠTransactionAspectSupport§¨ḄZ[»ᳮmṹஹJavamṹ!J1.protectedTransactioninfocreateTransactionlfNecessary(2.TransactionAttributetxAttr,finalStringjoinpointldentification){3.4.//Ifnonamespecified,applymethodidentifiedtionastransactionname.5.if(txAttr!=null&&txAttr.getNameO==null)(6.txAttr=newDelegatingTransactionAttribute(txAttr){7.publicStringgetName(){8.returnjoinpointIdentification9,s)10.)½

6611.)12.13.Transactionstatusstatus=null;14.if(txAttr!=null){15.஻Qxᵨᡃ@¦¾ḄZ[¿À¡,ᨵZ[»ᳮᘤᩭZ[K~NOTransactioninfo16.status=getTransactionManager0.getTransaction(txAttr);17.)18.returnprepareTransactionlnfo(txAttr,joinpointldentification,status);19.)✌ᐜC8TransactionManagerGᑮ◤⌕ḄZ[KZ[Ḅ᪷Äᡃ@¦ḄZ[¿ÀKᙠAbstractTransactionManagereÅÆ9²᪗ÇḄ8Kᯠ᪵ḄZ[ÉP◤⌕ᐹlḄPlatformTransactionManagerᩭKÊQxÅÆ9Z[ḄËÌsJavamṹᔣ1.publicfinalTransactionStatusgetTransaction(TransactionDefinitiondefinition)throwsTransactionException{2.Objecttransaction=doGetTransaction();3..............4.5.if(definition==null){6.஻᝞MZ[¡Ðᨵ¿ÀKᡃ@ᵨSpringÑÒḄ¿ÀU±7.definition=newDefaultTransactionDefinition();8.}9.10.if(isExistingTransaction(transaction)){11.//Existingtransactionfound->checkpropagationbehaviortofindouthowtobehave.12.returnhandleExistingTransaction(definition,transaction,debugEnabled);13.)14.15.//Checkdefinitionsettingsfornewtransaction.16.஻Õ☢®Pᵨ¿À¡ᩭᡃ@◤⌕ḄZ[½Ö᝞×Øឋ¶~ÙឋÚ

6717.஻ᨬÜa8eḄ¡ᦈÞqᩭ¢ᑮTransactionstatuseNO½18.if(definition.getTimeoutOcheckpropagationbehaviortofindouthowtobehave.23.if(definition.getPropagationBehavior0==Transact!onDefinition.PROPAGAT10N_MANDAT0RY){24.thrownewIllegalTransactionStateException(25.^Transactionpropagation'mandatoryKbutnoexistingtransactionfound");26.)27.elseif(definition.getPropagationBehavior()==TransactionDefinition.PROPAGATION_REQUIRED||28.definition.getPropagationBehavior()==TransactionDefinition.PROPAGAT10N_REQUIRES_NEW||29.definition.getPropagationBehavior()==TransactionDefinition.PROPAGAT10N_NESTED){30.஻QxPZê»ᳮᘤZ[ḄᙢUKìí8eGᑮḄ¡¢ᑮTransactionstatusefKᒹïÆᩭḄZ[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.)©ḼC8DᵨprepareTransactionlnfo_ᡂZ[ḄÇᜓK8eGᑮḄ¡óᙠTransactioninfoIJe×⌴~a¡¶õö½Javamṹ!J

681.protectedTransactionInfoprepareTransactionlnfo(2.TransactionAttributetxAttr,Stringjoinpointldentification,Transactionstatusstatus){3.4.Transactioninfotxlnfo=newTransactioninfo(txAttr,joinpointIdentification);5.if(txAttr!=null){6..............7.//~᪵Ḅ◤⌕aᙠgetTransactioneGᑮḄTransactionStatus¢÷UTransactionInfoeᩭ஺8.txlnfo.newTransactionStatus(status);9.}10.else{11...............12.)13.14.//öZ[¡ᑮõ15.txlnfo.bindToThread();16.returntxlnfo;17.)íZ[Ḅ¡NO,ᯠÜjᑮᐸøḄZ[»ᳮmṹ:Javamṹ~1protectedvoidcommitTransactionAfterReturning(Transactionlnfotxlnfo){2if(txlnfo!=null&&txlnfo.hasTransaction0){3if(logger.isDebugEnabledO){4logger,debug(/?Invokingcommitfortransactionon"+txlnfo.getJoinpointldentificationO);5)6this,transactionManager.commit(txlnfo.getTransactionStatus());7)8)C8transactionManagerIZ[ᜐᳮKᒹï´µúƶûµḄüýZ[KᐹlḄZ[ₒᳮᘤᵫᵨᡝ஺Javaṹ1.protectedvoidcompleteTransactionAfterThrowing(TransactionInfotxlnfo,Throwableex){

692.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........................12.try{13.this,transactionManager.commit(txlnfo.getTransactionStatus());14.)15.16.)17.18.protectedvoidcommitTransactionAfterReturning(Transactionlnfotxlnfo){19.if(txlnfo!=null&&txlnfo.hasTransaction0){20..............21.this,transactionManager.commit(txlnfo.getTransactionStatus());22.}23.}Spring)*+,ṹ-transactionManager./01ᜐᳮḄ*./5AOPᒹ78ᑮ:;ᡃ=>ᑮ?5@ABᡝCDEFGḄ01ᜐᳮ8SpringHIJ5KLMNḄ஺᝞PQRᵨSG01ᜐᳮ8*ᐸCUVWX8ᡃ=Y+Zὃ\]Ḅ^_`Javaṹa1.TransactionDefinitiontd=newDefaultTransactionDefinition0;2.Transactionstatusstatus=transactionManager.getTransaction(td);3.try{4..................஻:;Iᡃ=Ḅc1@d5.}catch(ApplicationExceptione){

706.transactionManager.rollback(status);7.throwe8.)9.transactionManager.commit(status);10ᡃ=>ᑮ:;⌱f5ghḄ01ijDefaultTransactionDefinition,akᙠmn0ᱥḄ*]pᑮTransactionstatus,ᯠr)*stuᵨ01vᳮᘤḄxᐵ@dz{|ᡂ01ᜐᳮ஺EFG01ᜐᳮ~a᪵CD5Ḅ*8I?ᵨ5EFḄ@d8◤⌕-ឋḄfᜐᳮ8◤⌕᦮*᦮ᔠᑮSpringAOP᪾]IoCᘤ]Ḅ*஺☢ᡃ=⌱fᐹḄtransactionManager-DataSourceTransactionManagerᩭ>>ᐸ]01ᜐᳮḄCD`a᪵Ḅ)*RᵨAbstractP1atformTransactionManagerRᵨ@d8:D5-ᐹ¡¢xᐵḄ01vᳮᘤ£NḄ¤78U᝞commitOJavaṹ!J1.publicfinalvoidcommit(Transactionstatusstatus)throwsTransactionException{2..............3.DefaultTransactionStatusdefStatus=(DefaultTransactionStatus)status;4.if(defStatus.isLocalRolIbackOnly()){5......................6.processRolIback(defStatus);7.return;8.)9.........................10.processRolIback(defStatus);11.............12.)13.14.processCommit(defStatus);15.))*-TransactionstatusḄᐹ¥᝱Ḅᑨ¨8ᩭ©ᐹḄ01ᜐᳮ`JavaṹI-J1.privatevoidprocessCommit(DefaultTransactionStatusstatus)throwsTransactionException{2.try{

713.booleanbeforeCompletionlnvokedfalse;4.try(5.triggerBeforeCommit(status);6.triggerBeforeCompletion(status);7.beforeCompletionlnvoked=true;8.booleanglobalRollbackOnly=false;9.if(status.isNewTransactionO||isFailEar1yOnG1oba1Ro11backOn1y()){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.):@dḄCDᵫᐹḄtransactionManagerᩭCD8U᝞ᙠDataSourceTransactionManager:JavaṹÇ1.protectedvoiddoCommit(DefaultTransactionStatusstatus)2.஻:;pᑮÉᙠTransactioninfo]ÊËmnÌḄ013.DataSourceTransactionObjecttxObject=(DataSourceTransactionObject)status.getTransactionO;4.5.஻:;pᑮ01ÍḄᦪÏÐÑt6.Connectioncon=txObject.getConnectionHolder().getConnectionO;7.8.try(9.஻:;)*ᦪÏÐÑtᩭÒÓ0110.con.commit();

7211.)12.13.)14.15.protectedvoiddoRolIback(DefaultTransactionStatusstatus){16.DataSourceTransactionObjecttxObject=(DataSourceTransactionObject)status.getTransaction();17.Connectioncon=txObject.getConnectionHolder().getConnection();18.if(status.isDebugO){19.logger,debug(//RollingbackJDBCtransactiononConnection["+con+20.)21.try{22.஻:;)*ᦪÏÐÑtᩭØÙ0123.con.rolIback();24.)25.catch(SQLExceptionex){26.thrownewTransactionSystemException(Z/CouldnotrollbackJDBCtransaction”,ex);27.)28.)ᡃ=>ᑮᙠDataSourceTransactionManager]ᨬrHIÓßconnectionᩭCD01ḄÒÓrollbacko᦮EFG01ᜐᳮI01ᜐᳮᙠSpringA0P]Ḅáᵨ8ᡃ=>ᑮ5âÌḄRᵨSpringAOPḄ^_8ᙠSpringEFG01ᜐᳮḄãṹ]ᡃ=Y+>ᑮ`1.ä᪵¤7ᔜæça¡¢Ḅ01ᜐᳮṹ2.ä᪵fឋèéᔠ01ᜐᳮṹᩭ|ᡂêḄ01ᜐᳮëᶍ3.ä᪵ᮣîḄRᵨSpringAOP᪾஺᝞P{ïéᔠð☢ḄSpringAOPḄãṹᩭñò8ᳮóY{ôõö÷஺======================7==============================================Springãṹó᪆(ù)`SpringAOP]-úûᘤuᵨḄCDð☢ᡃ=ᑖ᪆5SpringAOPCD]pᑮProxy-ýḄ*8☢ᡃ=>>ᙠSpringAOP]úûᘤþIä᪵ÿᵨḄProxy᪵ᵨḄᡈὅSpring᪵ᡃA0P!"Ḅ#ᙠJdkDynamicAopProxy,-ᡂProxy/0Ḅ1᎛3Java6ṹl-'J1.returnProxy.newProxylnstance(classLoader,proxiedlnterfaces,this);

73IJḄthisKᦪ/MḄInvocationHandler/0,IJᡃḄJdkDynamicAopProxyPQRISTUVProxy/0ḄWᦪXᵨḄ1᎛ISInvocationHandlerḄinvokeYZ[X\Wᦪᵨ]☢ᡃ__ISYZḄPQ3Java6ṹᔣ1.publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{2.Methodinvocationinvocation=null;3.ObjectoldProxy=null;4.booleansetProxyContext=false;5.6.TargetSourcetargetSource=this,advised.targetSource;7.ClasstargetClass=null;8.Objecttarget=null;9.10.try(11.//Tryspecialrulesforequals()methodandimplementationofthe12.//AdvisedAOPconfigurationinterface.13.14.if(!this.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.returnnewInteger(hashCode());22.}23.if(Advised,class==method.getDeclaringClass())(24.//serviceinvocationsonProxyConfigwiththeproxyconfig

7425.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.//Maybenul1.Getaslateaspossibletominimizethetimewe஻own஻thetarget37.//incaseitcomesfromapool.38.//IJᑮ᪗/0ḄᙢYVᯠIS᪗/0"ᩭSPᡈὅSᓫḄJAVA/039.target=targetSource.getTarget();40.if(target!=null){41.targetClass=target.getClass();42.)43.44.//gettheinterceptionchainforthismethod45.//IJḄᘤ46.Listchain=this,advised.advisorChainFactory.getlnterceptorsAndDynamidnterceptionAdvice(47.this,advised,proxy,method,targetClass);48.49.//Checkwhetherwehaveanyadvice.Ifwedont,we(3anfallbackondirect50.//reflectiveinvocationofthetarget,andavoidcreatingaMethodinvocation.51.//᝞ᨵ¡ᘤ¢£ᡃ¤Tᵨ᪗Ḅ/MYZ52.if(chain.isEmpty()){53.//WecanskipcreatingaMethodinvocation:justinvokethetargetdirectly54.//NotethatthefinalinvokermustbeanInvokerInterceptorsoweknowitdoes

7555.//nothingbutareflectiveoperationonthetarget,andnohotswappingorfancyproxying56.retVal=AopUtils.invokeJoinpointUsingReflection(target,method,args);57.}58.else{59.//Weneedtocreateamethodinvocation...60.//invocation=advised.getMethodlnvocationFactory().getMethodInvocation(61.//proxy,method,targetClass,target,args,chain,advised);62.//᝞ᨵᘤḄ¡¢£◤⌕ᵨᘤ¨©ªᵨ᪗/0Ḅ«MYZ63.//IJ¬᪀⌼SReflectiveMethodlnvocationᩭPQ]☢ᡃ[_ISReflectiveMethodlnvocation°64.invocation=newReflectiveMethodlnvocation(65.proxy,target,method,args,targetClass,chain);66.67.//proceedtothejoinpointthroughtheinterceptorchain68.//IJ¬ReflectiveMethodlnvocationᩭᵨᘤ±«MḄ᪗YZ69.retVal=invocation,proceed();70.}71.72.//massagereturnvalueifnecessary73.if(retVal!=null&&retVal==target&&method.getReturnType().islnstance(proxy)){74.//Specialcase:itreturned"this஻andthereturntypeofthemethodistype-compatible75.//NotethatwecanSthelpifthetargetsets76.//areferencetoitselfinanotherreturnedobject.77.retVal=proxy;78.}79.returnretVal;80.)

7681.finally{82.if(target!=null&&!targetSource.isStatic())(83.//musthavecomefromTargetSource84.targetSource.releaseTarget(target);85.}86.87.if(setProxyContext){88.//restoreoldproxy89.AopContext.setCurrentProxy(oldProxy);90.)91.)92.)ᡃᐜ__᪗/0YZḄᵨIJ¬AopUtilsḄYZᵨ-³ᵨ´µ¶ᑴᩭ/᪗/0ḄYZ¸¹ᵨ3Java6ṹ!'J1.publicstaticObjectinvokeJoinpointUsingReflection(Objecttarget,Methodmethod,Object[]args)2.throwsThrowable{3.4.//Usereflectiontoinvokethemethod.5.//ᑭᵨ»µ¶ᑴᑮ«MḄYZ¼½ᵨinvoke6.try{7.if(IModifier.isPublic(method.getModifiers())II118.!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.)

7718.catch(11legalArgumentExceptionex){19.thrownewAopInvocationException(ZAOPconfig□rationseemstobeinvalid:triedcallingmethod[஻+20.method+஻]ontarget[஻+target+஻/ex);21.)22.catch(IllegalAccessExceptionex){23.thrownewAopInvocationException(Z/Couldntaccessmethod:஻+method,ex);24.)25.)/ᘤḄᵨᜐᳮᙠReflectiveMethodlnvocationJPQḄ:Java6ṹ!J1.publicObjectproceed()throwsThrowable{2.//Westartwithanindexof-1andincrementearly.3.//IJ¤Tᵨ᪗/0ḄYZᨵᘤḄᵨᡈὅᘤÃÄᵨÅRIScurrentInterceptorindexḄÆÇÈ04.if(this,currentInterceptorIndex==this,interceptorsAndDynamicMethodMatchers.size()){5.returninvokejoinpoint();6.}7.8.ObjectinterceptorOrlnterceptionAdvice=9.this.interceptorsAndDynamicMethodMatchers.get(this.currentInterceptorIndex);10.if(interceptorOrlnterceptionAdviceinstanceofInterceptorAndDynamicMethodMatcher){11.//Evaluatedynamicmethodmatcherhere:staticpartwillalreadyhave12.//beenevaluatedandfoundtomatch.13.//IJ«MḄᘤ᝞ᘤÉᓛËḄÌḄÍ¢ᵨᘤḄinvokeYZ14.InterceptorAndDynamicMethodMatcherdm=15.(InterceptorAndDynamicMethodMatcher)interceptorOrlnterceptionAdvice;16.if(dm.methodMatcher.matches(this,method,this.targetClass,this,arguments)){

7817.returndm.interceptor,invoke(nextlnvocation());18.)19.else{20.//Dynamicmatchingfailed.21.//Skipthisinterceptorandinvokethenextinthechain.22.//᝞ᘤᓛËÎÌ¢ᵨ]SᘤIS1᎛ᘤḄÏÐᢣÒ©Ó¼Ô6ᵨVÕḄproceedYZ23.this.currentlnterceptorlndex++;24.returnproceed();25.)26.)27.else{28.//It'saninterceptor,sowejustinvokeit:Thepointcutwillhave29.//beenevaluatedstaticallybeforethisobjectwasconstructed.30.return((Methodinterceptor)interceptorOrlnterceptionAdvice).invoke(nextinvocation());32.)IJÖVÕḄᘤÉ×ᙠᘤḄÏÐ᪗ØÙcloneᑮSMethodinvocation/0RᵨVÕḄᘤ᡻¹Å¨©[ÛÜÝḼᑮISᘤ᡻¹]☢Ḅ¹[Ô6ḄᵨÌ☢ISproceed:Java6ṹ!J1.privateReflectiveMethodlnvocationnextinvocation()throwsCloneNotSupportedException{2.ReflectiveMethodInvocationinvocation=(ReflectiveMethodinvocation)clone();3.invocation,currentInterceptorIndex=this,currentlnterceptorlndex+1;4.invocation,parent=this;5.returninvocation;6.)IJḄnextinvocationÃÄᒹàRVÕḄḄáâãäᡃ_ᑮᙠInterceptor,ḄPQå᝞TransactioninterceptorḄPQ,3Java6ṹiJ

791.publicObjectinvoke(finalMethodinvocationinvocation)throwsThrowable{2............஻IJTransactioninterceptoræᐭḄèéᜐᳮ6ṹᡃ[ᙠ©☢ᑖ᪆èéᜐᳮPQḄ1᎛¸¹ᑖ᪆3.try{4.஻IJ/ËÐḄᘤ¸¹Ô6ᜐᳮḄᵨ5.retVal=invocation,proceed();6.}7஻ḕᶍR±èéᜐᳮḄîïᜐᳮ6ṹTransactioninterceptoræᐭḄᜐᳮ8.else{9.try{10.Objectresult=((CalIbackPreferringP1atformTransactionManager)getTransactionManager()).execute(txAttr,11.newTransactionCallback()(12.publicObjectdoInTransaction(TransactionStatusstatus){13.஻IJTransactioninterceptoræᐭ/èéᜐᳮḄ6ṹ14.Transactionlnfotxlnfo=prepareTransactioninfo(txAttr,joinpointldentification,status);15.஻IJ/ËÐḄᘤ¸¹Ô6ᜐᳮḄᵨTḼðḼᘤ¸¹ᜐᳮ16.try{17.returninvocation,proceed();18.)19//ḕᶍR±èéᜐᳮḄîïᜐᳮ6ṹTransactioninterceptoræᐭḄᜐᳮ20.}ñÌ☢Ḅᑖ᪆ᡃ_ᑮRSpringA0PḄáâPQå᝞Spring᪵ᑮProxy,᪵ᑭᵨJAVAProxyÉ×´µ¶ᑴ/ᵨᡝḄᘤ¸¹ᜐᳮ஺==========================8======================================Springôõöṹ÷᪆(11)3SpringøùúHibernateḄPQ0/RûᐹýQ¨©ᓄRÿᩖḄᢝᓄḄ஺SpringᵨὅSpringḄ0/RᫀḄᵨᔜᢝᓄᐹ᝞HibernateB

80!☢ᡃ$%Spring+Hibernate2ḄSpring345678ᓫḄᒈ᪆஺Spring=HinberanateḄ>?@LocalSessionFactoryBeanᩭJᡂḄL@67ᔆBeanḄ34ᙠOPAbstractSessionFactoryBean2RJavaUṹW1,/**2.*L@FactoryBean◤⌕34Ḅ`abc`defgḄsessionFactoryḄh3.*/4.publicObjectgetObject(){5.returnthis.sessionFactory;6.)L7hᙠafterPropertySet2wxRJavaUṹ1.publicvoidafterPropertiesSet0throwsException{2.஻L7buiIdSessionFactory@>?eᑮSessionFactoryḄᙢ3.SessionFactoryrawSf=buildSessionFactory();4.஻LᵨProxybᐭ=getCurrentSessionḄeᑮᐵḄsession5.this.sessionFactory=wrapSessionFactorylfNecessary(rawSf);6.)ᡃ$ᐜSessionFactory@᪵ḄL7bᒹHibernateḄSessionFactoryḄRJavaUṹ!J1.protectedSessionFactorybuildSessionFactory()throwsException{2.SessionFactorysf=null;3.4.//CreateConfigurationinstance.5.Configurationconfig=newConfigurationO;6.7.஻L>?ᦪ¡¢£ᳮᘤLobHanderᑮHolder2L7Holder@67ThreadLocal§¨,L᪵L©ª¢%«¬w8.if(this.dataSource!=null){9.//MakegivenDataSourceavailableforSessionFactoryconfiguration.

8110.configTimeDataSourceHolder.set(this.dataSource)H.O}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.஻L@ᵨHibernateḄᔜ7³ឋḄ>?LᵨConfigurationPᩭµ¶L©ᦪ¡25.try{26.//Setconnectionreleasemode஻on_close஻asdefault.27.//ThiswasthecaseforHibernate3.0;Hibernate3.1changed28.//itto஻auto஻(i.e.zSafter_statementz/orz/after_transactionzz).29.//However,forSpring*sresourcemanagement(inparticularfor30.//HibernateTransactionManager),஻on_close஻isthebetterdefault.31.config.setProperty(Environment.RELEASE_CONNECTIONS,ConnectionRe1easeMode.ON_CLOSE.toStringO);32.33.if(!isExposeTransactionAwareSessionFactory())(34.//NotexposingaSessionFactoryproxywithtransaction-aware35.//getCurrentSession()method->setHibernate3.1CurrentSessionContext36.//implementationinstead,providingtheSpring-managedSessionthatway.

8237.//CanbeoverriddenbyacustomvalueforcorrespondingHibernateproperty.38.config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,39.஻org.springframework.orm.hibernate3.SpringSessionContextz);40.}41.42.if(this.entityinterceptor!=null){43.//SetgivenentityinterceptoratSessionFactorylevel.44.config,setinterceptor(this,entitylnterceptor);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

8365.)66.)67.68.if(this,configLocations!=null){69.for(inti=0;i

8493.Environment.TRANSACTION_MANAGER_STRATEGY,LocalTransactionManagerLookup.class.getName0);94.)95.96.if(this.mappingLocations!=null){97.//RegistergivenHibernatemappingdefinitions,containedinresourcefiles.98.for(inti=0;i

85120.for(inti=0;i1){138.config.setCacheConcurrencystrategy(className,strategyAndRegion[0],strategyAndRegion[l]);139.)140.elseif(strategyAndRegion.length>0){141.config.setCacheConcurrencystrategy(className,strategyAndRegion[0]);142.}

86143.)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(collRole,strategyAndRegion[0]);157.)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");

87166.StringlistenerType=(String)entry.getKey();167.ObjectlistenerObject=entry.getValue();168.if(listenerObjectinstanceofCollection){169.Collectionlisteners=(Collection)listenerObject;170.EventListenerslistenerRegistry=config.getEventListeners();171.Object[]listenerArray=172.(0bject[])Array,newlnstance(listenerRegistry.getListenerClassFor(listenerType),listeners,size0);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.//L@᪷¡Configuration>?SessionFactoryḄᙢ186.logger,info("BuildingnewHibernateSessionFactoryzz);187.this.configuration=config;188.sf=newSessionFactory(config);189.)190.஻ᨬÇÈ«¬wḄª¢ÉÊ191.finally{192.if(this.dataSource!=null){193.//ResetDataSourceholder.

88194.configTimeDataSourceHolder.set(nul1)Ë195.i196.197.if(this.JtaTransactionManager!=null){198.//ResetTransaetionManagerhoider.199.configTimeTransactionManagerHoIder.set(null);200.1201.202.if(this.lobHandler!=null){203.//ResetLobHandlerholder.204.configTimeLobHandlerHolder.set(nul1)Ë205.)206.)207.208.//Executeschemaupdateifrequested.209.if(this.schemaUpdate){210.updateDatabaseSchema();211.)212.213.returnsf;214.)Wc`Íᵨorg.hibernate,cfg.Configurationᩭeᑮ◤⌕ḄSessionFactory:JavaUṹiJ1.protectedSessionFactorynewSessionFactory(Configurationconfig)throwsHibernateException{2.returnconfig,buiIdSessionFactory();3.)ᡠᡃ$LᑮLocalSessionFactoryᜧÑÒᑮḄ67Ódª¢>?ᯠÇÕᡂSessionFactoryḄÖᵨËfᯠLᙠeᑮSessionFactory×ÇØ◤⌕=sessionḄ£ᳮÖ6©ᜐᳮ-ᵨ67ProxyÚÛ=getCurrentSessionbÜÝÞËJavaUṹ,:J

891.஻Lᐜ᪷¡fgḄSessionFactoryḄPßeᑮProxy,ᯠÇᐭSpringwxàḄgetCurrentSessionᘤ2.protectedSessionFactorygetTransactionAwareSessionFactoryProxy(SessionFactorytarget){3.Classsflnterface=SessionFactory.class;4if(targetinstanceofSessionFactorylmplementor){5sflnterface=SessionFactoryImplementor.class;6}7return(SessionFactory)Proxy.newProxylnstance(sflnterface.getClassLoader(),8newClassa(sflnterface},newTransactionAwarelnvocationHandler(target));9)ᘤḄá4᝞!RJavaUṹ!J1.privatestaticclassTransactionAwareInvocationHand1erimplementsInvocationHandler{2.3.privatefinalSessionFactorytarget;4.5.publicTransactionAwarelnvocationHandler(SessionFactorytarget){6.this,target=target;7.)8.9.publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{10.//InvocationonSessionFactory/SessionFactorylmplementorinterfacecomingin...11.//L=getCurrentSessionbÜÝeᑮ67fgwḄsessionâãᵨᡝ12.if(method.getName().equals("'getCurrentSession஻)){13.//HandlegetCurrentSessionmethod:returntransactionalSession,ifany.14.try{15.returnSessionFactoryUtils.doGetSession((SessionFactory)proxy,false);

9016.)17.catch(IllegalStateExceptionex){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.returnnewInteger(hashCode());28.)29.30.//L@◤⌕æÝḄSessionFactoryḄç᪗b31.try{32.returnmethod,invoke(this,target,args);33.}34.catch(InvocationTargetExceptionex){35.throwex.getTargetException();36.}37.)38.)ᡃ$getCurrentSessionḄ34ᙠSessionFactoryUtils2RJavaUṹ!'J1.privatestaticSessiondoGetSession(2.SessionFactorysessionFactory,InterceptorentityInterceptor,3.SQLExceptionTrans1atorjdbcExceptionTranslator,booleanallowCreate)4.throwsHibernateException,IllegalStateException{

915.6.Assert.notNull(sessionFactory,“NoSessionFactoryspecifiedZ7);7.8.஻L7TransactionSynchronizationManagerḄResource@67ThreadLocal§¨sessionFactory@67ᓫîïThreadLocal@«¬wḄ9.஻L᪵%34Hiberante2ðᵨḄThreadLocalḄsession£ᳮñᑴ10.SessionHoldersessionHolder=(SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)Ë11.if(sessionHolder!=null&&!sessionHolder.isEmpty()){12.//pre-boundHibernateSession13.Sessionsession=null;14.if(TransactionSynchronizationManager.isSynchronizationActive()&&15.sessionHolder.doesNotHoIdNonDefaultSession()){16.//Springtransactionmanagementisactive->17.//registerpre-boundSessionwithitfortransactionalflushing.18.session=sessionHolder.getValidatedSessionO;19.if(session!=null&&!sessionHolder.isSynchronizedWithTransaction()){20.logger,debug(zzRegisteringSpringtransactionsynchronizationforexistingHibernateSession");21.TransactionSynchronizationManager.registersynchronization(22.newSpringSessionSynchronization(sessionHolder,sessionFactory,jdbcExceptionTranslator,false));23.sessionHolder.setSynchronizedWithTransaction(true);24.//SwitchtoFlushMode.AUTO,aswehavetoassumeathread-boundSession25.//withFlushMode.NEVER,whichneedstoallowflushingwithinthetransaction.

9226.FlushModeflushModesession.getFlushMode();27.if(flushMode.lessThan(FlushMode.COMMIT)&&28.ITransactionSynchronizationManager.isCurrentTransactionReadOn1y()){29.session.setFlushMode(FlushMode.AUTO);30.sessionHolder.setPreviousFlushMode(flushMode);31.}32.}33.}34.else{35.//NoSpringtransactionmanagementactive->tryJTAtransactionsynchronization.36.session=getJtaSynchronizedSession(sessionHolder,sessionFactory,jdbcExceptionTranslator)B37.}38.if(session!=null){39.returnsession;40.)41.)42.஻Lc`ᡭ67Session43.logger,debug(zS0peningHibernateSession");44.Sessionsession=(entityInterceptor!=nu11?45.sessionFactory.openSession(entitylnterceptor):sessionFactory.openSession());46.47.//UsesameSessionforfurtherHibernateactionswithinthetransaction.48.//Threadobjectwillgetremovedbysynchronizationattransactioncompletion.49.//È÷ᡭḄSessionøᑮSessionHolder,ᯠÇøᑮThreadLocal☢ù«¬wÒᩭL7ThreadLocal@ᙠTransactionSynchronizationManager2>?àḄ᪷¡sessionFactoryᩭúd

9350.//ûü᪷¡ᜐᳮḄý᝱ᩭ>?sessionḄ³ឋ,᝞ÈFlushModeÿNever,sessionᜐᳮᐵὶᩭ51.if(TransactionSynchronizationManager.isSynchronizationActive()){52.//We'rewithinaSpring-managedtransaction,possiblyfromJtaTransactionManager.53.logger,debug(^RegisteringSpringtransactionsynchronizationfornewHibernateSession");54.SessionHolderholderToUse=sessionHolder;55.if(holderToUse==null){56.holderToUse=newSessionHolder(session);57.)58.else{59.holderToUse.addSession(session)60.)61.if(Transact!onSynchronizationManager.isCurrentTransactionReadOnly()){62.session.setFlushMode(FlushMode.NEVER);63.)64.TransactionSynchronizationManager.registerSynchronization(65.newSpringSessionSynchronization(holderToUse,sessionFactory,jdbcExceptionTranslator,true));66.holderToUse.setSynchronizedWithTransaction(true);67.if(holderToUse!=sessionHolder){68.Transact!onSynchronizationManager.bindResource(sessionFactory,holderToUse);69.)70.)71.else{72.//NoSpringtransactionmanagementactive->tryJTAtransactionsynchronization.73.registerJtaSynchronization(session,sessionFactory,jdbcExceptionTranslator,sessionHolder);74.}75.

9476.//CheckwhetherweareallowedtoreturntheSession.77.if(!allowCreate&&!isSessionTransactional(session,sessionFactory)){78.closeSession(session);79.thrownewIllegalStateException(zSNoHibernateSessionboundtothread,஻+80.“andconfigurationdoesnotallowcreationofnon-transactionalonehere");81.}82.83.returnsession;84.)OPQRᙠSpringTUᵨHiberanteḄSessionFactoryXYSessionZḄ[ᜓ]^_ᙠO`aẠc_ᵨᡝeXfgUᵨHibenqateTemplateᩭUᵨHibernateḄ0/Rhi_XjkᑮḄm᪵ORm`executeḄopqJavarṹI'J1.publicObjectexecute(HibernateCalIbackaction,booleanexposeNativeSession)throwsDataAccessException{2.Assert.notNull(action,“Callbackobjectmustnotbenull");3.஻OPuᑮvwḄHibernateḄSession4.Sessionsession=getSessionO;5.booleanexistingTransaction=SessionFactoryUtiIs.isSessionTransactional(session,getSessionFactory());6.if(existingTransaction){7.logger,debug("Foundthread-boundSessionforHibernateTemplatezS);8.)9.10.FlushModepreviousFlushMode=null;11.try{12.previousFlushMode=applyFlushMode(session,existingTransaction);13.enableFilters(session);14.SessionsessionToExpose=(exposeNativeSession?session:createSessionProxy(session));15.஻OPRopḄᐭy16.Objectresult=action.doInHibernate(sessionToExpose);

9517.flushlfNecessary(session,existingTransaction)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.finally31.//᝞~O`pᵨḄᙠm`T_32.if(existingTransaction){33.logger,debug(Z/Notclosingpre-boundHibernateSessionafterHibernateTemplate_/);34.disableFilters(session);35.if(previousFlushMode!=null){36.session.setFlushMode(previousFlushMode);37.)38.)஻ᔲᑣSessionᐵ39.else{40.//NeverusedeferredcloseforanexplicitlynewSession.41.if(isAlwaysUseNewSession()){42.SessionFactoryUtils.closeSession(session);43.)44.else{45.SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session,getSessionFactory());46.)47.)48.)49.)

96ᡃkk᪵uᑮḄSessionḄ_ᯠUᵨSessionFactoryUtilsḄdoGetSession:Javarṹ!J1.protectedSessiongetSessionO{2.if(isAlwaysUseNewSession()){3.returnSessionFactoryUtils.getNewSession(getSessionFactory(),getEntityInterceptor());4.}5.elseif(!isAllowCreateO){6.returnSessionFactoryUtils.getSession(getSessionFactory(),false);7.)8.else(9.returnSessionFactoryUtils.getSession(10.getSessionFactory(),getEntityInterceptor(),getJdbcExceptionTranslator());11.)12.)O᪵ᡃQeXᐸḄTemplate᪵UᵨHibernateḄahi_UᵨḄ᎛SpringᡃSessionḄᐵ_ᜐᳮḄZw-O`¡k¢ᜧᜧ¤ᵨᡝḄUᵨ஺==============9======================Spring¦rṹ§᪆(©)qSpririRAcegi᪾«␺ᩗḄ®¯°ᓫᑖ᪆m³SpringAcegiḄ¦rṹ®¯qServlet.FilterḄ®¯AuthenticationProcessingFiIterµ¶Web⚓☢Ḅ¹ºg»-ᙠAbstractProcessingFilter¼᦮`¹ºg»Ḅ¾¿qJavarṹ1.publicvoiddoFiIter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)2.throwslOException,ServletException{3.஻OPÁ¹RÂRÃᔠServletRequest/SevletResponseḄ⌕Æ4.if(!(requestinstanceofHttpServletRequest)){5.thrownewServletException(Z/CanonlyprocessHttpServletRequest"");6.)7.8.if(!(responseinstanceofHttpServletResponse)){

979.thrownewServletException("CanonlyprocessHttpServletResponse_/);10.)11.12.HttpServletRequesthttpRequest=(HttpServletRequest)request;13.HttpServletResponsehttpResponse=(HttpServletResponse)response;14.஻᪷ÈHttpServletRequestHttpServletResponseᩭÉʹº15.if(requiresAuthentication(httpRequest,httpResponse))(16.if(logger.isDebugEnabledO){17.logger,debug(z_Requestistoprocessauthentication");18.)19.஻OP¼AcegiTḄAuthenticationÍᩭᢝᨵÐᐵḄᵨᡝ¹ºËÌ20.AuthenticationauthResult;21.22.try(23.onPreAuthentication(httpRequest,httpResponse);24.஻OPḄᐹÒ¹ºg»ÓᡲÕÖ×Øᡂ_Ú᝞AuthenticationProcessingFi1terᩭØᡂaÛWeb⚓☢Ḅᵨᡝ¹º25.authResult=attemptAuthentication(httpRequest);26.}catch(AuthenticationExceptionfailed){27.//Authenticationfailed28.unsuccessfulAuthentication(httpRequest,httpResponse,failed);29.30.return;31.)32.33.//Authenticationsuccess34.if(continueChainBeforeSuccessfulAuthentication){35.chain.doFi1ter(request,response);36.)37.஻Øᡂ¹ºÝḄÝÞ]^_Ú᝞ßàᑮÐḄ⚓☢

9838.successfulAuthentication(httpRequest,httpResponse,authResult);39.40.return;41.)42.43.chain.doFiIter(request,response);44.)ᙠAuthenticationProcessingFiIterTḄᐹÒ¹ºg»RO᪵Ḅ:Javarṹ!:J1.publicAuthenticationattemptAuthentication(HttpServletRequestrequest)2.throwsAuthenticationException{3.஻OPHttpServletRequestTuᑮᵨᡝ¹ºḄᵨᡝáâṹ4.Stringusername=obtainUsername(request);5.Stringpassword=obtainPassword(request);6.7.if(username==null){8.username=஻஻ã9.)10.11.if(password==null){12.password=஻஻ã13.)14.஻OP᪷ÈuᑮḄᵨᡝáâṹä᪀⌼m`AuthenticationÍçèÕAuthenticationManagerÉʹº_P☢ᒹêᵨᡝḄᵨᡝáâṹËÌ15.UsernamePasswordAuthenticationTokenauthRequest=newUsernamePasswordAuthenticationToken(username,password);16.17.//PlacethelastusernameattemptedintoHttpSessionforviews18.request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,username);19.20.//Allowsubclassestosetthe"details"property21.setDetaiIs(request,authRequest);22.஻OPµ¶AuthenticationManagerÉʹºg»

9923.returnthis.getAuthenticationManager().authenticate(authRequest);24.)ᙠAcegi᪾«T_ÉʹºîᳮḄï⌕×RAuthenticationManager,ᡃkkðR᪵ÉʹºîᳮḄ-¹ºḄpᵨᐭyRauthenticateᙠAbstractAuthenticationManagerḄ®¯Tq஻ORÉʹºḄñᦪ_óom`AuthenticationÍᩭôõ¹ºḄö~_ᐸTᒹêᵨᡝḄ¹ºËÌ_ᩗ▲vø_O`AuthenticationùXÝúᣴᩗ¾ᙽUᵨ—Javarṹ!J1.஻᝞~¹ºᜫÿᙠ2.publicfinalAuthenticationauthenticate(AuthenticationauthRequest)3.throwsAuthenticationException{4.try{஻▭Ḅᜐᳮᡃ☢ᵨProviderManagerᩭ!"ᐹ$Ḅ%ᐭḄ'ᦪauthRequest☢)*ᒹ,-.HttpServletRequest/ᑮḄᵨᡝ2ᐭḄᵨᡝ345ṹ5.AuthenticationauthResult=doAuthentication(authRequest);6.copyDetaiIs(authRequest,authResult);7.8.returnauthResult;9.}catch(AuthenticationExceptione){10.e.setAuthentication(authRequest);11.throwe;12.)13.)ᙠProviderManager78▭Ḅ9:Ꮇ<ᵨᦪ=>ᩭ?@ᵨᡝABCJavaDṹ!J1.publicAuthenticationdoAuthentication(Authenticationauthentication)2.throwsAuthenticationException{3.஻@/GHIḄproviderJḄKDᘤᙠGHḄM᎛OPGHQRprovider,ᡃGHḄDaoAuthenticationProviderᩭ!"Sᵨᦪ=>ᩭT?ᵨᡝḄᵨᡝ345ṹAB஺4.Iteratoriter=providers,iterator();

1005.6.ClasstoTest=authentication.getClassO;7.8.AuthenticationExceptionlastException=null;9.10.while(iter.hasNext()){11.Authenticationproviderprovider=(AuthenticationProvider)iter.next();12.13.if(provider,supports(toTest)){14.logger,debug(/zAuthenticationattemptusing஻+provider.getClass().getName());15.஻Rresultᒹ,-/ᑮḄAB16.Authenticationresult=null;17.18.try{஻provider78ᜐᳮḄ19.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.publishEvent(newAuthenticationSuccessEvent(result));29.30.returnresult;31.)32.}33.)34.35.if(lastException==null){36.lastException=newProviderNotFoundException(messages.getMessage(^ProviderManager.providerNotFoundz,

10137.newObject[]{toTest.getName()},“NoAuthenticationProviderfoundfor{0}஻))38.)39.40.//ᩭᦻḄᘤ41.StringclassName=exceptionMappings.getProperty(lastException.getClass().getName());42.AbstractAuthenticationEventevent=null;43.44.if(className!=null){45.try{46.Classclazz=getClass().getClassLoader().loadClass(className);47.Constructorconstructor=clazz.getConstructor(newClass[]{48.Authentication,class,AuthenticationException.class49.});50.Objectobj=constructor,newlnstance(newObject[](authentication,lastException});51.Assert.isInstanceOf(AbstractAuthenticationEvent.class,obj,"MustbeanAbstractAuthenticationEvent஻)52.event=(AbstractAuthenticationEvent)obj;53.}catch(ClassNotFoundExceptionignored){}54.catch(NoSuchMethodExceptionignored){}55.catch(IllegalAccessExceptionignored){}56.catch(InstantiationExceptionignored){}57.catch(InvocationTargetExceptionignored){}58.)59.60.if(event!=null){61.publishEvent(event);62.}else{63.if(logger.isDebugEnabledO){

10264.logger,debug(zNoeventwasfoundfortheexception஻+lastException.getClassO.getNameO);65.)66.)67.68.//Throwtheexception69.throwlastException;70.}ᡃ☢¡¡ᙠDaoAuthenticationProvider¢᪵.ᦪ=>@¤¥ḄAB78ᵨᡝḄᙠSḄ¦§AbstractUserDetailsAuthenticationProvider©ª-Ḅᜐᳮ«¬CJavaDṹI.J1.publicAuthenticationauthenticate(Authenticationauthentication)2.throwsAuthenticationException{3.Assert.isInstanceOf(UsernamePasswordAuthenticationToken•class,authentication,4.messages.getMessage(^AbstractUserDetailsAuthenticationProvider.onlySupportsz,5.“OnlyUsernamePasswordAuthenticationTokenissupported"));6.7.//@/ᵨᡝ2ᐭḄᵨᡝ38.Stringusername=(authentication.getPrincipal()==null)?NONE_PROVIDEDZ:authentication.getNameO;9.//᝞MH-¶?.¶?·@P¸?ᐭḄᵨᡝAB-UserDetail,º»ᘤ¼?ᙠᦪ=>ḄᵨᡝAB᪵½¾ᵨ¿ÀÁ·ᦪ=>@-10.booleancacheWasUsed=true;11.UserDetailsuser=this.userCache.getUserFromCache(username);12.஻Ãᨵ@ᑮABḄᙢË17.user=retrieveUser(username,(UsernamePasswordAuthenticationToken)authentication);

10318.}catch(UsernameNotFoundExceptionnotFound)19.if(hideUserNotFoundExceptions){20.thrownewBadCredentialsException(messages.getMessage(21.“AbstractUserDetaiIsAuthenticationProvider.badCredentialsz,“Badcredentials"))22.}else{23.thrownotFound;24.25.}26.27.Assert.notNull(user,“retrieveUserreturnednullaviolationoftheinterfacecontract");28.)29.30.if(!user.isAccountNonLocked()){31.thrownewLockedException(messages.getMessage(zAbstractUserDetaiIsAuthenticationProvider.locked”,32.“Useraccountislocked"));33.34.35.if(!user.isEnabledO){36.thrownewDisabledException(messages.getMessage(z/AbstractUserDetaiIsAuthenticationProvider.disabled”,37.“Userisdisabled"));38.39.40.if(!user.isAccountNonExpired()){41.thrownewAccountExpiredException(messages,getMessage(z/AbstractUserDetaiIsAuthenticationProvider.expired”,42.“Useraccounthasexpired"))43.44.45.//Thischeckmustcomehere,aswedon'twanttotellusers46.//aboutaccountstatusunlesstheypresentedthecorrectcredentials

10447.try{஻ᙠretrieveUser.ᦪ=>/ᑮᵨᡝḄABᙠadditionalAuthenticationChecks78¤Ìᵨᡝ2ᐭ4º»ᘤ¼ḄᵨᡝAB48.஻᝞᪀⌼ÏRAuthentication¤ÐᩭÑPÒḄᣴᩗᵨ᝞¾Õ␺ᩗ49.additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken)authentication);50.}catch(AuthenticationExceptionexception){51.if(cacheWasUsed){52.//Therewasaproblem,sotryagainafterchecking53.//we'reusinglatestdata(ienotfromthecache)54.cacheWasUsed=false;55.user=retrieveUser(username,(UsernamePasswordAuthenticationToken)authentication);56.additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken)authentication);57.}else{58.throwexception;59.}60.)61.62.if(!user.isCredentialsNonExpired0){63.thrownewCredentialsExpiredException(messages.getMessage(64.zAbstractUserDetailsAuthenticationProvider.credentialsExpiredz,“Usercredentialshaveexpiredz));65.)66.஻᪷=¸☢Ḅ¶?Ù©¾⌕ÈÛ¸ḄᵨᡝAB?ᐭ¶?PÜÀᵨ67.if(!cacheWasUsed){68.this.userCache.putUserlnCache(user);69.)70.71.ObjectprincipalToReturn=user;72.73.if(forcePrincipalAsString){74.principalToReturn=user.getUsernameO;75.}76.஻ᨬÒÞßAuthenticationàá-ÜPÒḄᣴᩗᵨ

10577.returncreateSuccessAuthentication(principalToReturn,authentication,user);78J79.஻ÉᵨUserDetailService·â㺻ᘤ¼ᵨᡝABḄᙢË.äᙢËâã⌕¡âãᵨᡝABæMÞß.ᦪ=>ÞßḄABçABèᑮ-UserDetails¤Ð·-84.try{85.loadedUser=this.getUserDetailsServiceO.loadUserByUsername(username);86.}catch(DataAccessExceptionrepositoryProblem){87.thrownewAuthenticationServiceException(repositoryProblem.getMessage(),repositoryProb1em);88.)89.90.if(loadedUser=null){91.thrownewAuthenticationServiceException(92.zUserDetailsServicereturnednull,whichisaninterfacecontractviolation");93.}94.returnloadedUser;95.)☢ᡃêëᑖ᪆ÏJdbcDaoImpR§ᩭ¡¡ᐹ$¢᪵.ᦪ=>/ᑮᵨᡝABḄCJavaDṹ1J1.publicclassJdbcDaoImplextendsJdbcDaoSupportimplementsUserDetailsService{2./rStaticfields/initializers=====================3.஻⚜©ªIḄ¤ïðñò¤¥óôõḄᦪ=>⊤᪀÷OPøù©ªïðñò¤¥ᱯ©Ḅᵨᡝᦪ=>⊤Ḅ<û

1064.publicstaticfinalStringDEF_USERS_BY_USERNAME_QUERY=5."SELECTusername,password,enabledFROMusersWHEREusername=?஻6.publicstaticfinalStringDEF_AUTHORITIES_BY_USERNAME_QUERY=7."SELECTusername,authorityFROMauthoritiesWHEREusername=?஻8.9.//Instancefields—10.஻ᵨSpringJDBCᩭᦪ11.protectedMappingSqlQueryauthoritiesByUsernameMapping+12.protectedMappingSqlQueryusersByUsernameMapping;13.privateStringauthoritiesByUsernameQuery;14.privateStringrolePrefix=஻஻+15.privateStringusersByUsernameQuery;16.privatebooleanusernameBasedPrimaryKey=true;17.18./PConstructors====================================19.஻ᙠ=>ᓄ@ᦪABCDEFGHI⚜KLḄSQLEF20.publicJdbcDaoImpl(){21.usersByUsernameQuery=DEF_USERS_BY_USERNAME_QUERY;22.authoritiesByUsernameQuery=DEF_AUTHORITIES_BY_USERNAME_QUERY;23.)24.25./PMethods===================""26.27.protectedvoidaddCustomAuthorities(Stringusername,Listauthorities){}28.29.publicStringgetAuthoritiesByUsernameQuery(){30.returnauthoritiesByUsernameQuery;31.}

10732.33.publicStringgetRolePrefix(){34.returnrolePrefix;35.)36.37.publicStringgetUsersByUsernameQuery(){38.returnusersByUsernameQuery;39.)40.41.protectedvoidinitDaoOthrowsApp1icationContextException{42.initMappingSqlQueries();43.)44.45./**46.*ExtensionpointtoallowotherMappingSqlQueryobjectstobesubstitutedinasubclass47.*/48.protectedvoidinitMappingSqlQueries0{49.this.usersByUsernameMapping=newUsersByUsernameMapping(getDataSource());50.this.authoritiesByUsernameMapping=newAuthoritiesByUsernameMapping(getDataSource());51.)52.53.publicbooleanisUsernameBasedPrimaryKey(){54.returnusernameBasedPrimaryKey;55.)56.஻defᦪᵨᡝhiḄᐹklm57.publicUserDetailsloadUserByUsername(Stringusername)58.throwsUsernameNotFoundException,DataAccessException{59.//᪷ᵨᡝoᙠᵨᡝ⊤AfᑮᵨᡝhirᒹtᵨᡝoruṹwᵨᡝdᔲᨵᦔḄhi60.Listusers=usersByUsernameMapping.execute(username);61.62.if(users.size()==0){63.thrownewUsernameNotFoundException(஻Usernotfound");64.)65.஻e|ᔠAḄ~IᨵᦔḄᵨᡝ

10866.UserDetailsuser=(UserDetails)users.get(0);//containsnoGrantedAuthority[]67.஻ᙠᩗ▲⊤AefᵨᡝḄᩗ▲hir᪵Ḅᩗ▲|ᔠᵨᡝ68.ListdbAuths=authoritiesByUsernameMapping.execute(user.getUsername());69.70.addCustomAuthorities(user.getUsername(),dbAuths);71.72.if(dbAuths.size()==0){73.thrownewUsernameNotFoundException(஻UserhasnoGrantedAuthority"");74.)75.஻᪷fᑮḄᩗ▲|ᔠᩭHḄUserᵨ76.GrantedAuthority[]arrayAuths=(GrantedAuthority)dbAuths.toArray(newGrantedAuthority[dbAuths.size()])+77.78.StringreturnUsername=user.getUsername();79.80.if(!usernameBasedPrimaryKey){81.returnUsername=username;82.)83.84.returnnewUser(returnUsername,user.getPassword(),user.isEnabledO,true,true,true,arrayAuths);85.)86.87.publicvoidsetAuthoritiesByUsernameQuery(StringqueryString){88.authoritiesByUsernameQuery=queryString;89.)90.91.publicvoidsetRolePrefix(StringrolePrefix)92.this.rolePrefix=rolePrefix;93.}94.95.publicvoidsetUsernameBasedPrimaryKey(booleanusernameBasedPrimaryKey){

10996.this.usernameBasedPrimaryKeyusernameBasedPrimaryKey;97.)98.99.publicvoidsetUsersByUsernameQuery(StringusersByUsernameQueryString){100.this.usersByUsernameQuery=usersByUsernameQueryString;101.)102.103./rInnerClasses=============================104.105./**106.*dᵨSpringJDBCḄᦪrᐹkὃJDBCḄᑖ᪆rḄᵨdBᦪCDfᑮḄ|ᔠᣚI|ᔠ-¡¢ᓫḄ0/R¤¥107.*/108.protectedclassAuthoritiesByUsernameMappingextendsMappingSqlQuery{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.GrantedAuthorityImplauthority=newGrantedAuthorityImpl(roleName);119.120.returnauthority;121.)122.)123.124./**125.*Queryobjecttolookupauser.

110126.*/127.protectedclassUsersByUsernameMappingextendsMappingSqlQuery(128.protectedUsersByUsernameMapping(DataSourceds){129.super(ds,usersByUsernameQuery);130.dec1areParameter(newSqlParameter(Types.VARCHAR));131.compile();132.)133.134.protectedObjectmapRow(ResultSetrs,intrownum)135.throwsSQLException{136.Stringusername=rs.getString(1)+137.Stringpassword=rs.getString(2)+138.booleanenabled=rs.getBoolean(3);139.UserDetailsuser=newUser(username,password,enabled,true,true,true,140.newGrantedAuthority[]{newGrantedAuthoritylmpl(rrH0LDERr/)});141.142.returnuser;143.}144.)145.)©ᦪAfᑮᵨᡝhirªd«ᵨᡝ¬ᐭḄhiwᦪᵨᡝhiḄ«lmr«lmᙠDaoAuthenticationProvider:Java¯ṹI'J1.஻UserDetaild©ᦪACDᑮḄrauthenticationd©ᵨᡝ¬ᐭAfᑮḄ2.protectedvoidadditionalAuthenticationChecks(UserDetailsuserDetails,3.UsernamePasswordAuthenticationTokenauthentication)4.throwsAuthenticationException{5.Objectsalt=null;

1116.7.if(this.saltSource!=null){8.salt=this.saltSource.getSalt(userDetails);9.}10.஻᝞²ᵨᡝ³ᨵ¬ᐭuṹr´µ¶·¸¹11.if(authentication.getCredentials()==null)(12.thrownewBadCredentialsException(messages.getMessage(13.^AbstractUserDetailsAuthenticationProvider.badCredentials/z,“Badcredentials77),14.includeDetailsObject?userDetails:null);15.}16.஻efᵨᡝ¬ᐭḄuṹ17.StringpresentedPassword=authentication,getCredentials()==null?஻஻:authentication.getCredentiaIs().toStringO;18.஻ᑨ¾ᵨᡝ¬ᐭḄuṹd¿dwᦪḄuṹÀrᵨpasswordEncoderᩭᦪḄuṹÁÂu19.//᝞²¿Àr¶·¸¹r᝞²Àᑣ␺ᩗᡂÆ20.if(!passwordEncoder.isPasswordValid(21.userDetails.getPasswordO,presentedPassword,salt)){22.thrownewBadCredentialsException(messages.getMessage(23.rzAbstractUserDetai1sAuthenticationProvider.badCredentialsr/,“Badcredentials^),24.includeDetailsObject?userDetails:null);25.}26.)Ç☢ᑖ᪆É᦮AcegiËÌḄlmr©AuthenticationProcessingFilterAÍÎHttpÏÐfᑮᵨᡝ¬ᐭḄᵨᡝowuṹrÑᵨᡝ¬ᐭḄËÌhiÒÓÔᑮAuthenticationAᢝᨵÖ×⌴ÙAuthenticatioManagerᩭ«ᙠÚÛÜḄᵨᡝhiᩭÝᡂ᦮␺ᩗ஺␺ᩗÝᡂÒBᨵᦔḄᵨᡝhiÔᙠAuthenticationAḄᣴᩗàᙽᵨ஺ᙠᐹkḄ␺ᩗlmArᵨÉᡃãHäḄᔜæProviderçḄUserDetailServicewEncoderᩭÝᡂÀḄèeÚÛᘤÜᵨᡝᦪçêᵨᡝ¬ᐭḄËÌhiḄ«ë஺=================================10================================Springì¯ṹÂ᪆íᓝïðSpringAcegi᪾òᣴᩗḄ¤¥

112ᡃã©FilterSecurityInterceptorᡃã©ᐭóôôõ᪵ᣴᩗḄ:Java¯ṹ1.஻dÍÎᘤÍÎHTTPÏÐḄᐭ2.publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)3.throwslOException,ServletException{4.FilterInvocationfi=newFilterInvocation(request,response,chain);5.invoke(fi);6.)7.஻dᐹkḄÍÎᵨ8.publicvoidinvoke(Filterinvocationfi)throwsI0Exception,ServletException{9.if((fi.getRequest()!=null)&&(fi.getRequest().getAttribute(FILTER_APPLIED)!=null)10.&&observeOncePerRequest){11.஻ᙠ~÷løᐰúCûª¿ÒüýT12.fi.getChain().doFilter(fi.getRequest(),fi.getResponse());13.}else14.஻d~÷ᦈᑮÀḄÏÐr◤⌕ᐰ᪗-FILTER_APPLIED,ᨵ"#$%&'Ḅᐰ)*15.if(fi.getRequest()!=null){16.fi.getRequest().setAttribute(FILTER_APPLIED,Boolean.TRUE);17.)18.஻HIJᐰ)ḄᙢL19.InterceptorStatusTokentoken=super,beforeinvocation(fi);20.஻UḼᔣXYᘤ[᡻]21.try{22.fi.getChain().doFilter(fi.getRequest(),fi.getResponse());23.}finally{24.super.afterInvocation(token,null)e25.}26.)27.)

113ᡃghhᙠAbstractSecurityInterceptorJj᪵lHTTP"#&ᐰḄ:JavapṹIJ1.protectedInterceptorStatusTokenbeforeinvocation(Objectobject){2.Assert.notNull(object,“Objectwasnull");3.4.if(!getSecureObjectClass().isAssignableFrom(object.getClass())){5.thrownewIHegalArgumentException("Securityinvocationattemptedforobject஻6.+object.getClass().getName()7.+஻butAbstractSecurityInterceptoronlyconfiguredtosupportsecureobjectsoftype:஻8.+getSecureObjectClassO);9.)10.஻HI{|}FilterSecurityInterceptorḄObjectDefinitionSource~ឋH~ឋ}*Ḅᐰ11.ConfigAttributeDefinitionattr=this.obtainObjectDefinitionSource().getAttributes(object);12.13.if(attr==null){14.if(rejectPublidnvocations){15.thrownewIllegalArgumentException(16.“NopublicinvocationsareallowedviathisAbstractSecurityInterceptor.஻17.+“Thisindicatesaconfigurationerrorbecausethe஻18.+zAbstractSecurityInterceptor.rejectPublidnvocationspropertyissetto'true'");19.)20.21.if(logger.isDebugEnabledO){22.logger,debug(''Publicobject-authenticationnotattempted");23.}24.25.publishEvent(newPublicInvocationEvent(object))e26.

11427.returnnull;//nofurtherworkpost-invocation28.)29.30.31.if(logger.isDebugEnabledO){32.logger,debug("Secureobject:஻+object.toStringO+஻eConfigAttributes:஻+attr.toStringO);33.)34.஻HISecurityContextHolder|Authenticationlᙠ%ᑮSecurityContextHolder35.if(SecurityContextHolder.getContext().getAuthentication()==null){36.credentialsNotFound(messages.getMessage("AbstractSecurityInterceptor.authenticationNotFound/,37.஻AnAuthenticationobjectwasnotfoundintheSecurityContext"),object,attr);38.)39.40.//᝞☢ᨵᜐᳮ␺ᩗHI◤⌕l␺ᩗ]ᜐᳮ41.Authenticationauthenticated;42.43.if(!SecurityContextHolder.getContext().getAuthentication().isAuthenticatedO||alwaysReauthenticate){44.try{஻ᵨ}ḄAuthenticationManagerᜐᳮ␺ᩗ᝞␺ᩗ$ᡂ¡¢£¤¥¦ᜐᳮ45.authenticated=this.authenticationManager.authenticate(SecurityContextHolder.getContext()46.,getAuthenticationO);47.}catch(AuthenticationExceptionauthenticationException){48.throwauthenticationException;49.}50.51.//Wedontauthenticated.setAuthentication(true),becauseeachprovidershoulddothat52.if(logger.isDebugEnabledO){53.logger,debug(^SuccessfullyAuthenticated:஻+authenticated.toStringO);54.)

11555.஻HI␺ᩗᡂ©ªᑮḄAuthentication«¬ᑮSecurityContextHolder®ᵨ56.SecurityContextHolder.getContext().setAuthentication(authenticated);57.}else{஻HIᜐᳮ☢¯°±²␺ᩗḄ"#ᐜSecurityContextHolder|ªAuthentication58.authenticatedSecurityContextHolder.getContext().getAuthentication();59.60.if(logger.isDebugEnabled()){61.logger,debug("PreviouslyAuthenticated"+authenticated.toStringO);62.)63.)64.65.//HJᜐᳮᣴᩗḄ²µ66.try(67.஻ᵨ}ḄAccessDecisionManagerᩭ]ᣴ68.this.accessDecisionManager.decide(authenticatedobject,attr);69.}catch(AccessDeniedExceptionaccessDeniedException(70.஻ᣴᩗ$ᡂᔣ᜜¸¹º»71.AuthorizationFailureEventevent=newAuthorizationFailureEvent(object,attr,authenticated,72.accessDeniedException);73.publishEvent(event);74.75.throwaccessDeniedException;76.)77.78.if(logger.isDebugEnabled0){79.logger,debug(^Authorizationsuccessful");80.}81.82.AuthorizedEventevent=newAuthorizedEvent(object,attr,authenticated);83.publishEvent(event);84.85.//HI᪀½¾RunAsManagerᩭ¿pÀḄAuthenticationlÁÂÃÄ®ᵨḄJNullRunAsManager%SecurityContextHolderḄAuthenticationlÅÆ

11686.AuthenticationrunAs=this.runAsManager.buildRunAs(authenticated,object,attr);87.88.if(runAs==null){89.if(logger.isDebugEnabled()){90.logger,debug(zRunAsManagerdidnotchangeAuthenticationobject");91.)92.93.//nofurtherworkpost-invocation94.returnnewInterceptorStatusToken(authenticated,false,attr,object);95.}else{96.if(logger.isDebugEnabled()){97.logger,debug(''SwitchingtoRunAsAuthentication:"+runAs.toStringO);98.)99.100.SecurityContextHolder.getContext().setAuthentication(runAs);101.102.//reverttotoken.AuthenticatedpostÇinvocation103.returnnewInterceptorStatusToken(authenticated,true,attr,object);104.}105.}ᑮHIᡃgᎷ}AffirmativeBased&AccessDecisionManagerÉJavapṹiJ1.஻HIÊË*ÌÍÎᑴ◤⌕ᐰἠÑÒ±²2.publicvoiddecide(Authenticationauthentication,0bjectobject,ConfigAttributeDefinitionconfig)3.throwsAccessDeniedException{4.஻HI|ª}ḄÓpᘤÔᔠ5.Iteratoriter=this.getDecisionVoters().iterator()6.intdeny=0;7.஻×®ᵨᔜ¾ᢗἠᘤ]ᢗἠÚlᢗἠ¥]Û8.while(iter.hasNext()){

1179.AccessDecisionVotervoter=(AccessDecisionVoter)iter,next();10.intresult=voter.vote(authentication,object,config);11.஻HJlᢗἠ¥]ᜐᳮ᝞⍗ᑮᐸἠ±²Þᣴᩗ±²᝞JßᩗᡈὅâlÞãäᢗἠ12.switch(result){13.caseAccessDecisionVoter.ACCESS_GRANTED:14.return;15.16.caseAccessDecisionVoter.ACCESS_DENIED17.஻HIlâlἠ]Ûᦪ18.deny++;19.20.break;21.22.default:23.break;24.)25.)26.஻᝞ᨵâlἠ¡¢£¤᦮¾ᣴᩗ$±²27.if(deny>0){28.thrownewAccessDeniedException(messages.getMessage(zAbstractAccessDecisionManager.accessDeniedz,29.“Accessisdenied"));30.}31.32.//HIlßᩗἠ]ᜐᳮhhJᐰJßᩗἠḄÌÊÃÄÁÂJ$±²ᵫallowIfAllAbstainDecisionsêëìᑴ33.checkAllowIfAHAbstainDecisions();34.)35.ᐹîḄᢗἠᵫᢗἠᘤ]ᡃgHI}*R36.publicintvote(Authenticationauthentication,Objectobject,ConfigAttributeDefinitionconfig){37.intresult=ACCESS_ABSTAIN;38.஻HI|ªḄᐰ}39.Iteratoriter=config.getConfigAttributes()40.41.while(iter.hasNext()){

11842.ConfigAttributeattribute=(ConfigAttribute)iter,next();43.44.if(this,supports(attribute)){45.result=ACCESS_DENIED;46.47.//HIl}Ḅᐰᣴᩗïð]ᑨòóJᓛ}ROLEõḄö⁐}48.//øᔊú¾}~ឋ᝞ᐸ¾ᓛ}ûüîᢝᨵḄGrantedAuthority,ᑣÿᐕ஺49.for(inti=0;i

119JavaEyeᨬt✌⚓fJava@Spring—SpringWṹᑖ᪆springWṹᑖ᪆-XmlBeanFactoryTὅcalmness▅T:6115O12ᩩ¢£¤¥O2007-04-26ᦈ¦W§ṹᑖ᪆Q9B¨©ª«¬Ḅ®¯Q°±²ᑏḄ§ṹ9´?ḄQµ¶·¸¹°º»Ḅ¤᎛Q½`¬¾¿ÀÁÂᩭQjoÃÄ©ªQ¢¬ḄÅᩭ¬Qᙠ^ÆÇÈ´?^ÉᦻË:ÌÍÎÏḄÐÑᨵB<ÓÔ஺Õᦻ\spring᪾×ḄXmlBeanFactoryjᐭPØfgᑖ᪆QÇȸ¹\ÙÚÛܺoḄÝÞßàᨵ◤⌕ḄÐÑBãḄÓÔ஺✌ᐜᩭᡭæjçèḄ§ṹQᡃlé°ᑮ᝞ì§ṹJava§ṹ⚗1.publicclassXmlBeanFactoryextendsDefaultListableBeanFactory{2.3.privatefinalXmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(this);4.5.publicXmlBeanFactory(Resourceresource)throwsBeansException{6.this(resource,null);7.)8.9.publicXmlBeanFactory(Resourceresource,BeanFactoryparentBeanFactory)throwsBeansException{10.super(parentBeanFactory);11.this,reader.loadBeanDefinitions(resource);12.)13.14.)^<èḄ§ṹîÛᓫQB<ᡂᕒ:ñòó<᪀⌼öᦪQF^Æᡃlw\°Qᨬù⌕ḄᙢÝᙠûᨬSB<᪀⌼öᦪ

120Java§ṹ!J1.super(parentBeanFactory);2.this,reader.loadBeanDefinitions(resource);᱄ᔆ᱄Ḅ᪀⌼$ᦪ&'▭)ᨬ+,-᱄ᔆ./ᑮḄparentBeanFactoryᡂᕒ678&9:67ᙠAbstractBeanFactory>78?@Ḅ&A9:᱄ᔆ,BCD⌴ᑮF>7GH./஺J᦮:8ᨬL⌕ḄᙢOP&QRS@&TḄUḄVWXmlBeanDefinitionReader9:XMLḄReader]^_resource8`,aḄbcᦻefghbeanḄ?@஺ijᩭᡃmᡭoXmlBeanDefinitionReaderḄloadBeanDefinitionsOp&ᡃmqrᑮᙠ9:OpstṹH&vᵨP:xRyxzḄOp&AzᦪEncodedResourceḄ:'|&9:'▭)ResourceḄ:ᒹ~&ᵨᩭ./^_ḄEncodeḄ&ijᩭᡃmrvᵨḄloadBeanDefinitionsOp&9:Opsᨬ⌕ḄᑖJavatṹ!J1.InputSourceinputSource=newInputSource(inputStream);2.if(encodedResource.getEncodingO!=null){3.inputSource.setEncoding(encodedResource.getEncoding());4.)5.returndoLoadBeanDefinitions(inputSource,encodedResource.getResource());9sḄUḄ^_ᒹ~ᡂ:InputSource,xResourcezᦪD⌴ᑮdoLoadBeanDefinitionsOpJavatṹiJ1.DocumentBuiIderFactoryfactory=createDocumentBuiIderFactory();2.if(logger.isDebugEnabledO){3.logger,debug(z&UsingJAXPimplementation[஻+factory+)4.)5.DocumentBuiIderbuilder=createDocumentBuiIder(factory);

1216.Documentdoc=builder,parse(inputSource);7.returnregisterBeanDefinitions(doc,resource);9:OpḄUḄUPᯠ&P^_¤¥ᡂDocument67&ᯠ+vᵨregisterBeanDefinitionsOp&9sy¦§¨¤¥&yP¤Ḅ©ª«rrᐵJAXPḄ®¯஺ijᩭᡃmᡭoregisterBeanDefinitionsOpJavatṹ1.publicintregisterBeanDefinitions(Documentdoc,Resourceresource)throwsBeansException{2.XmlBeanDefinitionParserparser=3.(XmlBeanDefinitionParser)BeanUtils.instantiateClass(this.parserClass);4.returnparser.registerBeanDefinitions(this,doc,resource);5.)9s³´P:XmlBeanDefinitionParseriµḄ'¶&9:iµḄᐹ¸DefaultXmlBeanDefinitionParser,9:iµ¹ºᓫ&¼ᨵregisterBeanDefinitions:Op&9:OpḄᵨ,¹¾P&ᵨᩭ¿ÀBeanḄ?@Ḅ&ᡠÂÃÄOpḄRÅ?⌕ÆÇᨵÈ@&9᪵qÂÊËrᜧᭆP¤ᐸᵨ&ÏÐP¹Ñ▅gtṹḄÓÔ஺Õ©yÑÃ&ᡃmᡭoDefaultXmlBeanDefinitionParserḄregisterBeanDefinitionsOp&9:¤¥XMLbcᦻeḄ᪶×P&ᡭoregisterBeanDefinitionsOp+ᡃmrᑮ᝞jt”JavatṹiJ1.publicintregisterBeanDefinitions(BeanDefinitionReaderreader,Documentdoc,Resourceresource)2.throwsBeanDefinitionStoreException{3.4.this.beanDefinitionReader=reader;5.this.resource=resource;6.7.logger,debug('"Loadingbeandefinitions");8.Elementroot=doc.getDocumentElement();9.஻Þßᓄ᪷ᐗã10.initDefaults(root);11.if(logger.isDebugEnabledO){12.logger,debug(z&Defaultlazyinit'஻+getDefaultLazylnit()+஻'஻)

12213.logger,debug(''Defaultautowire'஻+getDefaultAutowire()+஻'஻)14.logger.debug(''Defaultdependencycheck'஻+getDefaultDependencyCheck()+஻'஻)15.)16.17.preProcessXml(root);//:çOpᵨ᡽é18.intbeanDefinitionCount=parseBeanDefinitions(root)஻¤¥bcḄ⌕Op19.if(logger.isDebugEnabledO){20.logger,debug(zzFound஻+beanDefinitionCount+஻elementsin஻+resource);21.}22.postProcessXml(root);஻:çOpᵨ᡽é23.24.returnbeanDefinitionCount;25Jᙠ9:Opí8&⌕ᵨ¤¥?@Ḅᨵî:Op&:initDefaults,—:parseBeanDefinitions,:Opᵨᩭ¤¥᪷ᐗãḄðឋḄ&|᝞lazy-init,autowireó&AparseBeanDefinitionsᵨᩭ¤¥ᐹ¸Ḅbean?@P&Oôtṹ᝞jJavatṹ1.protectedintparseBeanDefinitions(Elementroot)throwsBeanDefinitionStoreException{2.NodeListnl=root.getChildNodes();3.intbeanDefinitionCount=0;4.for(inti=0;i

12313.Stringaliasele.getAttribute(ALIAS_ATTRIBUTE)14.this.beanDefinitionReader.getBeanFactory().registerAlias(name,alias);15.)16.elseif(BEAN_ELEMENT.equals(node,getNodeName())){17.beanDefinitionCount++;18.BeanDefinitionHolderbdHolder=parseBeanDefinitionElement(ele,false);19.BeanDefinitionReaderUtiIs.registerBeanDefinition(bdHo1der,this.beanDefinitionReader.getBeanFactory());20.}21.}22.)23.returnbeanDefinitionCount;24.)ᐸú᪗üᐹ¸᝞ý¤¥9syÑÃ&þÿᜧ⌕beanḄᜐᳮᡃṹJavaṹIJ1.elseif(BEAN_ELEMENT.equals(node.getNodeName())){2.beanDefinitionCount++;3.BeanDefinitionHolderbdHolder=parseBeanDefinitionElement(ele,false);4.BeanDefinitionReaderUtiIs.registerBeanDefinition(bdHolder,this.beanDefinitionReader.getBeanFactory());5.)PQRᑮTbean᪗VḄW᎛ᡠZ[Ḅᜐᳮ\P]beanḄ^_Z[`ᑮparseBeanDefinitionElementabḄcTdᦪfPbeanᑣTᐗicjTdᦪ⊤lmbeanPᔲoᑁqḄbean,rZ[Ḅbeanst`PᑁqḄᡠuvfalseodᦪᡭxparseBeanDefinitionElementabf`ᑮTabfP]beanḄᑁyḄz{ᓫt}~ᕣᕣWᑮ~ᡠfᑏ}~Ḅf᪵ᱯḄᙢa஺]~ᨬᨵfPbeanḄ^_ᑮbeanFactoryTbeanFactoryḄ¡fPXmlBeanFactory~,mbeanFactoryPᙠnewḄW᎛¥⌴ᑮreaderḄfPm§¨[ṹJavaṹ!J

1241.privatefinalXmlBeanDefinitionReaderreader=newXmlBeanDefinitionReader(this);ª~f}~ᦻ¬odὃ¬~᝞°±²bean^_ᙽ¬oTdὃ´µ]ᐸ·¸¹ᨵᡠº»ᔳ½oWᒺ¿ᨵ┯ÁḄᙢaÂᢣZEo

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

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

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