spring and spring mvcWord文档格式.docx
《spring and spring mvcWord文档格式.docx》由会员分享,可在线阅读,更多相关《spring and spring mvcWord文档格式.docx(8页珍藏版)》请在冰点文库上搜索。
springandspringmvc@#@springandspringmvc@#@SpringandSpringMVCIn-DepthAnalysisTheCorepackageisthemostfundamentalpartoftheframeworkandprovidestheDependencyInjectionfeaturesallowingyoutomanagebeancontainerfunctionality.ThebasicconcepthereistheBeanFactory,whichprovidesafactorypatternremovingtheneedforprogrammaticsingletonsandallowingyoutodecoupletheconfigurationandspecificationofdependenciesfromyouractualprogramlogic.OntopoftheCorepackagesitstheContextpackage,providingawaytoaccessbeansinaframework-stylemanner,somewhatresemblingaJNDI-registry.Thecontextpackageinheritsitsfeaturesfromthebeanspackageandaddssupportfortextmessagingusinge.g.resourcebundles,event-propagation,resource-loadingandtransparentcreationofcontextsby,forexample,aservletcontainer.TheDAOpackageprovidesaJDBC-abstractionlayerthatremovestheneedtodotediousJDBCcodingandparsingofdatabase-vendorspecificerrorcodes.Also,theJDBCpackageprovidesawaytodoprogrammaticaswellasdeclarativetransactionmanagement,notonlyforclassesimplementingspecialinterfaces,butforallyourPOJOs(plainoldjavaobjects).TheORMpackageprovidesintegrationlayersforpopularobject-relationalmappingAPIs,includingJDO,HibernateandiBatis.UsingtheORMpackageyoucanuseallthoseO/R-mappersincombinationwithalltheotherfeaturesSpringoffers,likesimpledeclarativetransactionmanagementmentionedbefore.Spring’sAOPpackageprovidesanAOPAlliancecompliantaspect-orientedprogrammingimplementationallowingyoutodefine,forexample,method-interceptorsandpointcutstocleanlydecouplecodeimplementingfunctionalitythatshouldlogicallyspeakingbeseparated.Usingsource-levelmetadatafunctionalityyoucanincorporateallkindsofbehavioralinformationintoyourcode,alittlelike.NETattributes.Spring’sWebpackageprovidesbasicweb-orientedintegrationfeatures,suchasmultipartfunctionality,initializationofcontextsusingservletlistenersandaweb-orientedapplicationcontext.WhenusingSpringtogetherwithWebWorkorStruts,thisisthepackagetointegratewith.Spring’sWebMVCpackageprovidesaModel-View-Controllerimplementationforweb-applications.Spring’sMVCimplementationisnotjustanyimplementation,itprovidesacleanseparationbetweendomainmodelcodeandwebformsandallowsyoutousealltheotherfeaturesoftheSpringFrameworklikevalidation.Spring’swebMVCframeworkisdesignedaroundaDispatcherServletthatdispatchesrequeststohandlers,withconfigurablehandlermappings,viewresolution,localeandthemeresolutionaswellassupportforuploadfiles.ThedefaulthandlerisaverysimpleControllerinterface,justofferingaModelAndViewhandleRequest(request,response)method.Thiscanalreadybeusedforapplicationcontrollers,butyouwillprefertheincludedimplementationhierarchy,consistingof,forexampleAbstractController,AbstractCommandControllerandSimpleFormController.Applicationcontrollerswilltypicallybesubclassesofthose.Notethatyoucanchooseanappropriatebaseclass:
@#@Ifyoudon’thaveaform,youdon’tneedaFormController.ThisisamajordifferencetoStruts.Youcanuseanyobjectasacommandorformobject-there’snoneedtoimplementaninterfaceorderivefromabaseclass.Spring’sdatabindingishighlyflexible,forexample,ittreatstypemismatchesasvalidationerrorsthatcanbeevaluatedbytheapplication,notassystemerrors.Soyoudon’tneedtoduplicateyourbusinessobjects’propertiesasStringsinyourformobjects,justtobeabletohandleinvalidsubmissions,ortoconverttheStringsproperly.Instead,itisoftenpreferabletobinddirectlytoyourbusinessobjects.ThisisanothermajordifferencetoStrutswhichisbuiltaroundrequiredbaseclasseslikeActionandActionForm-foreverytypeofaction.AllyourregisteredbeansandallofSpring’sservicescanbeatyourfingertipsevenwithoutSpring’swebMVC.Springdoesn’tcompetewithStrutsorWebWorkinthisscenario,itjustaddressesthemanyareasthatthepurewebMVCframeworksdon’t,frombeanconfigurationtodataaccessandtransactionhandling.SoyouareabletoenrichyourapplicationwithaSpringmiddletierand/ordataaccesstier,evenifyoujustwanttouse,forexample,thetransactionabstractionwithJDBCorHibernate.FeaturesofSpringMVCSpring’swebmoduleprovidesawealthofuniquewebsupportfeatures,including:
@#@Clearseparationofroles-controller,validator,commandobject,formobject,modelobject,DispatcherServlet,handlermapping,viewresolver,etc.Eachrolecanbefulfilledbyaspecializedobject.SomeofthethebenefitsofusingSpringtocreateyourO/RmappingDAOsinclude:
@#@Easeoftesting.Spring’sinversionofcontrolapproachmakesiteasytoswaptheimplementationsandconfiglocationsofHibernateSessionFactoryinstances,JDBCDataSources,transactionmanagers,andmapperobjectimplementations(ifneeded).Thismakesitmucheasiertoisolateandtesteachpieceofpersistence-relatedcodeinisolation.Commondataaccessexceptions.SpringcanwrapexceptionsfromyouO/Rmappingtoolofchoice,convertingthemfromproprietary(potentiallychecked)exceptionstoacommonruntimeDataAccessExceptionhierarchy.Thisallowsyoutohandlemostpersistenceexceptions,whicharenon-recoverable,onlyintheappropriatelayers,withoutannoyingboilerplatecatches/throws,andexceptiondeclarations.Youcanstilltrapandhandleexceptionsanywhereyouneedto.RememberthatJDBCexceptions(includingDBspecificdialects)arealsoconvertedtothesamehierarchy,meaningthatyoucanperformsomeoperationswithJDBCwithinaconsistentprogrammingmodel.Generalresourcemanagement.SpringapplicationcontextscanhandlethelocationandconfigurationofHibernateSessionFactoryinstances,JDBCDataSources,iBATISSQLMapsconfigurationobjects,andotherrelatedresources.Thismakesthesevalueseasytomanageandchange.Springoffersefficient,easyandsafehandlingofpersistenceresources.Forexample:
@#@RelatedcodeusingHibernategenerallyneedstousethesameHibernateSessionforefficiencyandpropertransactionhandling.SpringmakesiteasytotransparentlycreateandbindaSessiontothecurrentthread,eitherbyusinganexplicit‘template’wrapperclassattheJavacodelevelorbyexposingacurrentSessionthroughtheHibernateSessionFactory(forDAOsbasedonplainHibernate3API).ThusSpringsolvesmanyoftheissuesthatrepeatedlyarisefromtypicalHibernateusage,foranytransactionenvironment(localorJTA).Integratedtransactionmanagement.SpringallowsyoutowrapyourO/Rmappingcodewitheitheradeclarative,AOPstylemethodinterceptor,oranexplicit‘template’wrapperclassattheJavacodelevel.Ineithercase,transactionsemanticsarehandledforyou,andpropertransactionhandling(rollback,etc)incaseofexceptionsistakencareof.Asdiscussedbelow,youalsogetthebenefitofbeingabletouseandswapvarioustransactionmanagers,withoutyourHibernate/JDOrelatedcodebeingaffected:
@#@forexample,betweenlocaltransactionsandJTA,withthesamefullservices(suchasdeclarativetransactions)availableinbothscenarios.Asanadditionalbenefit,JDBC-relatedcodecanfullyintegratetransactionallywiththecodeyouusetodoO/Rmapping.Thisisusefulfordataaccessthat’snotsuitableforO/Rmapping,suchasbatchprocessingorstreamingofBLOBs,whichstillneedstosharecommontransactionswithO/Rmappingoperations.Toavoidvendorlock-in,andallowmix-and-matchimplementationstrategies.WhileHibernateispowerful,flexible,opensourceandfree,itstillusesaproprietaryAPI.FurthermoreonecouldarguethatiBATISisabitlightweight,althoughit’sexcellentforuseinapplicationthatdon’trequirecomplexO/Rmappingstrategies.Giventhechoice,it’susuallydesirabletoimplementmajorapplicationfunctionalityusingstandardorabstractedAPIs,incaseyouneedtoswitchtoanotherimplementationforreasonsoffunctionality,performance,oranyotherconcerns.Forexample,Spring’sabstractionofHibernatetransactionsandexceptions,alongwithitsIoCapproachwhichallowsyoutoeasilyswapinmapper/DAOobjectsimplementingdataaccessfunctionality,makesiteasytoisolateallHibernate-specificcodeinoneareaofyourapplication,withoutsacrificinganyofthepowerofHibernate.HigherlevelservicecodedealingwiththeDAOshasnoneedtoknowanythingabouttheirimplementation.Thisapproachhastheadditionalbenefitofmakingiteasytointentionallyimplementdataaccesswithamix-and-matchapproach(i.e.somedataaccessperformedusingHibernate,andsomeusingJDBC,othersusingiBATIS)inanon-intrusivefashion,potentiallyprovidinggreatbenefitsintermsofcontinuingtouselegacycodeorleveragingthestrengthofeachtechnology.TheSpringtransactionabstractionSpringprovidesaconsistentabstractionfortransactionmanagement.ThisabstractionisoneofthemostimportantofSpring’sabstractions,anddeliversthefollowingbenefits:
@#@ProvidesaconsistentprogrammingmodelacrossdifferenttransactionAPIssuchasJTA,JDBC,Hibernate,iBATISDatabaseLayerandJDO.Providesasimpler,easiertouse,APIforprogrammatictransactionmanagementthanmostofthesetransactionAPIsIntegrateswiththeSpringdataaccessabstractionSupportsSpringdeclarativetransactionmanagementTraditionally,J2EEdevelopershavehadtwochoicesfortransactionmanagement:
@#@touseglobalorlocaltransactions.Globaltransactionsaremanagedbytheapplicationserver,usingJTA.Localtransactionsareresource-specific:
@#@forexample,atransactionassociatedwithaJDBC