spring框架简介外文翻译

spring框架简介外文翻译

ID:22650670

大小:86.50 KB

页数:26页

时间:2018-10-30

上传者:U-25942
spring框架简介外文翻译_第1页
spring框架简介外文翻译_第2页
spring框架简介外文翻译_第3页
spring框架简介外文翻译_第4页
spring框架简介外文翻译_第5页
资源描述:

《spring框架简介外文翻译》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库

xxxx大学xxx学院毕业设计(论文)外文文献翻译系部xxxx专业xxxx学生姓名xxxx学号xxxx指导教师xxxx职称xxxx2013年3月25 IntroducingtheSpringFrameworkTheSpringFramework:apopularopensourceapplicationframeworkthataddressesmanyoftheissuesoutlinedinthisbook.ThischapterwillintroducethebasicideasofSpringanddis-cussthecentral“beanfactory”lightweightInversion-of-Control(IoC)containerindetail.Springmakesitparticularlyeasytoimplementlightweight,yetextensible,J2EEarchi-tectures.Itprovidesanout-of-the-boximplementationofthefundamentalarchitecturalbuildingblockswerecommend.Springprovidesaconsistentwayofstructuringyourapplications,andprovidesnumerousmiddletierfeaturesthatcanmakeJ2EEdevelopmentsignificantlyeasierandmoreflexiblethanintraditionalapproaches.ThebasicmotivationsforSpringare:Toaddressareasnotwellservedbyotherframeworks.TherearenumerousgoodsolutionstospecificareasofJ2EEinfrastructure:webframeworks,persistencesolutions,remotingtools,andsoon.However,integratingthesetoolsintoacomprehensivearchitecturecaninvolvesignificanteffort,andcanbecomeaburden.Springaimstoprovideanend-to-endsolution,integratingspe-cializedframeworksintoacoherentoverallinfrastructure.Springalsoaddressessomeareasthatotherframeworksdon’t.Forexample,fewframeworksaddressgenerictransactionmanagement,dataaccessobjectimplementation,andgluingallthosethingstogetherintoanapplication,whilestillallowingforbest-of-breedchoiceineacharea.HencewetermSpringanapplicationframework,ratherthanawebframework,IoCorAOPframework,orevenmiddletierframework.Toallowforeasyadoption.Aframeworkshouldbecleanlylayered,allowingtheuseofindi-vidualfeatureswithoutimposingawholeworld25 viewontheapplication.ManySpringfeatures,suchastheJDBCabstractionlayerorHibernateintegration,canbeusedinalibrarystyleoraspartoftheSpringend-to-endsolution.Todelivereaseofuse.Aswe’venoted,J2EEoutoftheboxisrelativelyhardtousetosolvemanycommonproblems.Agoodinfrastructureframeworkshouldmakesimpletaskssimpletoachieve,withoutforcingtradeoffsforfuturecomplexrequirements(likedistributedtransactions)ontheapplicationdeveloper.ItshouldallowdeveloperstoleverageJ2EEservicessuchasJTAwhereappropriate,buttoavoiddependenceonthemincaseswhentheyareunnecessarilycomplex.Tomakeiteasiertoapplybestpractices.Springaimstoreducethecostofadheringtobestpracticessuchasprogrammingtointerfaces,ratherthanclasses,almosttozero.However,itleavesthechoiceofarchitecturalstyletothedeveloper.Non-invasiveness.Applicationobjectsshouldhaveminimaldependenceontheframework.IfleveragingaspecificSpringfeature,anobjectshoulddependonlyonthatparticularfeature,whetherbyimplementingacallbackinterfaceorusingtheframeworkasaclasslibrary.IoCandAOParethekeyenablingtechnologiesforavoidingframeworkdependence.Consistentconfiguration.Agoodinfrastructureframeworkshouldkeepapplicationconfigurationflexibleandconsistent,avoidingtheneedforcustomsingletonsandfactories.Asinglestyleshouldbeapplicabletoallconfigurationneeds,fromthemiddletiertowebcontrollers.Easeoftesting.Testingeitherwholeapplicationsorindividualapplicationclassesinunittestsshouldbeaseasyaspossible.Replacingresourcesorapplicationobjectswithmockobjectsshouldbestraightforward.25 Toallowforextensibility.BecauseSpringisitselfbasedoninterfaces,ratherthanclasses,itiseasytoextendorcustomizeit.ManySpringcomponentsusestrategyinterfaces,allowingeasycustomization.ALayeredApplicationFrameworkChapter6introducedtheSpringFrameworkasalightweightcontainer,competingwithIoCcontainerssuchasPicoContainer.WhiletheSpringlightweightcontainerforJavaBeansisacoreconcept,thisisjustthefoundationforasolutionforallmiddlewarelayers.BasicBuildingBlockspringisafull-featuredapplicationframeworkthatcanbeleveragedatmanylevels.Itconsistsofmulti-plesub-frameworksthatarefairlyindependentbutstillintegratecloselyintoaone-stopshop,ifdesired.Thekeyareasare:Beanfactory.TheSpringlightweightIoCcontainer,capableofconfiguringandwiringupJava-BeansandmostplainJavaobjects,removingtheneedforcustomsingletonsandadhocconfigura-tion.Variousout-of-the-boximplementationsincludeanXML-basedbeanfactory.ThelightweightIoCcontaineranditsDependencyInjectioncapabilitieswillbethemainfocusofthischapter.Applicationcontext.ASpringapplicationcontextextendsthebeanfactoryconceptbyaddingsupportformessagesourcesandresourceloading,andprovidinghooksintoexistingenviron-ments.Variousout-of-the-boximplementationsincludestandaloneapplicationcontextsandanXML-basedwebapplicationcontext.AOPframework.TheSpringAOPframeworkprovidesAOPsupportformethodinterceptiononanyclassmanagedbyaSpringlightweightcontainer.25 Itsupportseasyproxyingofbeansinabeanfactory,seamlesslyweavingininterceptorsandotheradviceatruntime.Chapter8dis-cussestheSpringAOPframeworkindetail.ThemainuseoftheSpringAOPframeworkistoprovidedeclarativeenterpriseservicesforPOJOs.Auto-proxying.SpringprovidesahigherlevelofabstractionovertheAOPframeworkandlow-levelservices,whichofferssimilarease-of-useto.NETwithinaJ2EEcontext.Inparticular,theprovisionofdeclarativeenterpriseservicescanbedrivenbysource-levelmetadata.Transactionmanagement.Springprovidesagenerictransactionmanagementinfrastructure,withpluggabletransactionstrategies(suchasJTAandJDBC)andvariousmeansfordemarcat-ingtransactionsinapplications.Chapter9discussesitsrationaleandthepowerandflexibilitythatitoffers.DAOabstraction.Springdefinesasetofgenericdataaccessexceptionsthatcanbeusedforcre-atinggenericDAOinterfacesthatthrowmeaningfulexceptionsindependentoftheunderlyingpersistencemechanism.Chapter10illustratestheSpringsupportforDAOsinmoredetail,examiningJDBC,JDO,andHibernateasimplementationstrategies.JDBCsupport.SpringofferstwolevelsofJDBCabstractionthatsignificantlyeasetheeffortofwritingJDBC-basedDAOs:theorg.springframework.jdbc.corepackage(atemplate/callbackapproach)andtheorg.springframework.jdbc.objectpackage(modelingRDBMSoperationsasreusableobjects).UsingtheSpringJDBCpackagescandelivermuchgreaterpro-ductivityandeliminatethepotentialforcommonerrorssuchasleakedconnections,comparedwithdirectuseofJDBC.TheSpringJDBCabstractionintegrateswiththetransactionandDAOabstractions.IntegrationwithO/Rmappingtools.Springprovidessupportclasses25 forO/RMappingtoolslikeHibernate,JDO,andiBATISDatabaseLayertosimplifyresourcesetup,acquisition,andrelease,andtointegratewiththeoveralltransactionandDAOabstractions.TheseintegrationpackagesallowapplicationstodispensewithcustomThreadLocalsessionsandnativetransac-tionhandling,regardlessoftheunderlyingO/Rmappingapproachtheyworkwith.WebMVCframework.SpringprovidesacleanimplementationofwebMVC,consistentwiththeJavaBeanconfigurationapproach.TheSpringwebframeworkenableswebcontrollerstobeconfiguredwithinanIoCcontainer,eliminatingtheneedtowriteanycustomcodetoaccessbusinesslayerservices.ItprovidesagenericDispatcherServletandout-of-the-boxcontrollerclassesforcommandandformhandling.Request-to-controllermapping,viewresolution,localeresolutionandotherimportantservicesareallpluggable,makingtheframeworkhighlyextensi-ble.ThewebframeworkisdesignedtoworknotonlywithJSP,butwithanyviewtechnology,suchasVelocity—withouttheneedforadditionalbridges.Chapter13discusseswebtierdesignandtheSpringwebMVCframeworkindetail.Remotingsupport.Springprovidesathinabstractionlayerforaccessingremoteserviceswithouthard-codedlookups,andforexposingSpring-managedapplicationbeansasremoteservices.Out-of-the-boxsupportisincludedforRMI,Caucho’sHessianandBurlapwebserviceprotocols,andWSDLWebServicesviaJAX-RPC.Chapter11discusseslightweightremoting.WhileSpringaddressesareasasdiverseastransactionmanagementandwebMVC,itusesaconsistentapproacheverywhere.Onceyouhavelearnedthebasicconfigurationstyle,youwillbeabletoapplyitinmanyareas.Resources,middletierobjects,andwebcomponentsareallsetupusingthesamebeanconfigurationmechanism.Youcancombineyourentire25 configurationinonesinglebeandefinitionfileorsplititbyapplicationmodulesorlayers;thechoiceisuptoyouastheapplicationdeveloper.Thereisnoneedfordiverseconfigurationfilesinavarietyofformats,spreadoutacrosstheapplication.SpringonJ2EEAlthoughmanypartsofSpringcanbeusedinanykindofJavaenvironment,itisprimarilyaJ2EEapplicationframework.Forexample,thereareconvenienceclassesforlinkingJNDIresourcesintoabeanfactory,suchasJDBCDataSourcesandEJBs,andintegrationwithJTAfordistributedtransactionmanagement.Inmostcases,applicationobjectsdonotneedtoworkwithJ2EEAPIsdirectly,improvingreusabilityandmeaningthatthereisnoneedtowriteverbose,hard-to-test,JNDIlookups.ThusSpringallowsapplicationcodetoseamlesslyintegrateintoaJ2EEenvironmentwithoutbeingunnecessarilytiedtoit.YoucanbuilduponJ2EEserviceswhereitmakessenseforyourapplication,andchooselighter-weightsolutionsiftherearenocomplexrequirements.Forexample,youneedtouseJTAastransactionstrategyonlyifyoufacedistributedtransactionrequirements.Forasingledatabase,therearealternativestrategiesthatdonotdependonaJ2EEcontainer.Switchingbetweenthosetransac-tionstrategiesismerelyamatterofconfiguration;Spring’sconsistentabstractionavoidsanyneedtochangeapplicationcode.SpringofferssupportforaccessingEJBs.Thisisanimportantfeature(andrelevanteveninabookon“J2EEwithoutEJB”)becausetheuseofdynamicproxiesascodelessclient-sidebusinessdelegatesmeansthatSpringcanmakeusingalocalstatelesssessionEJBanimplementation-level,ratherthanafundamen-talarchitectural,choice.25 ThusifyouwanttouseEJB,youcanwithinaconsistentarchitecture;however,youdonotneedtomakeEJBthecornerstoneofyourarchitecture.ThisSpringfeaturecanmakedevel-opingEJBapplicationssignificantlyfaster,becausethereisnoneedtowritecustomcodeinserviceloca-torsorbusinessdelegates.TestingEJBclientcodeisalsomucheasier,becauseitonlydependsontheEJB’sBusinessMethodsinterface(whichisnotEJB-specific),notonJNDIortheEJBAPI.SpringalsoprovidessupportforimplementingEJBs,intheformofconveniencesuperclassesforEJBimplementationclasses,whichloadaSpringlightweightcontainerbasedonanenvironmentvariablespecifiedintheejb-jar.xmldeploymentdescriptor.Thisisapowerfulandconvenientwayofimple-mentingSLSBsorMDBsthatarefacadesforfine-grainedPOJOs:abestpracticeifyoudochoosetoimplementanEJBapplication.UsingthisSpringfeaturedoesnotconflictwithEJBinanyway—itmerelysimplifiesfollowinggoodpractice.IntroducingtheSpringFrameworkThemainaimofSpringistomakeJ2EEeasiertouseandpromotegoodprogrammingpractice.Itdoesnotreinventthewheel;thusyou’llfindnologgingpackagesinSpring,noconnectionpools,nodistributedtransactioncoordinator.Allthesefeaturesareprovidedbyotheropensourceprojects—suchasJakartaCommonsLogging(whichSpringusesforallitslogoutput),JakartaCommonsDBCP(whichcanbeusedaslocalDataSource),andObjectWebJOTM(whichcanbeusedastransactionmanager)—orbyyourJ2EEapplicationserver.Forthesamereason,Springdoesn’tprovideanO/Rmappinglayer:Therearegoodsolutionsforthisproblemarea,suchasHibernateandJDO.Springdoesaimtomakeexistingtechnologieseasiertouse.Forexample,althoughSpringisnotinthebusinessoflow-leveltransaction25 coordination,itdoesprovideanabstractionlayeroverJTAoranyothertransactionstrategy.SpringisalsopopularasmiddletierinfrastructureforHibernate,becauseitprovidessolutionstomanycommonissueslikeSessionFactorysetup,ThreadLocalsessions,andexceptionhandling.WiththeSpringHibernateTemplateclass,implementationmethodsofHibernateDAOscanbereducedtoone-linerswhileproperlyparticipatingintransactions.TheSpringFrameworkdoesnotaimtoreplaceJ2EEmiddletierservicesasawhole.Itisanapplicationframeworkthatmakesaccessinglow-levelJ2EEcontainerser-viceseasier.Furthermore,itofferslightweightalternativesforcertainJ2EEservicesinsomescenarios,suchasaJDBC-basedtransactionstrategyinsteadofJTAwhenjustworkingwithasingledatabase.Essentially,Springenablesyoutowriteappli-cationsthatscaledownaswellasup.SpringforWebApplicationsAtypicalusageofSpringinaJ2EEenvironmentistoserveasbackboneforthelogicalmiddletierofaJ2EEwebapplication.Springprovidesawebapplicationcontextconcept,apowerfullightweightIoCcontainerthatseamlesslyadaptstoawebenvironment:Itcanbeaccessedfromanykindofwebtier,whetherStruts,WebWork,Tapestry,JSF,SpringwebMVC,oracustomsolution.Thefollowingcodeshowsatypicalexampleofsuchawebapplicationcontext.InatypicalSpringwebapp,anapplicationContext.xmlfilewillresideintheWEB-INFdirectory,containingbeandefini-tionsaccordingtothe“spring-beans”DTD.InsuchabeandefinitionXMLfile,businessobjectsandresourcesaredefined,forexample,a“myDataSource”bean,a“myInventoryManager”bean,anda“myProductManager”bean.Springtakescareoftheirconfiguration,theirwiringup,andtheirlifecycle.25 com.mysql.jdbc.Driverjdbc:mysql:mydstrueBydefault,allsuchbeanshave“singleton”scope:oneinstancepercontext.The“myInventoryManager”beanwillautomaticallybewiredupwiththedefinedDataSource,while“myProductManager”willinturnreceiveareferencetothe“myInventoryManager”bean.Thoseobjects(traditionallycalled“beans”inSpringterminology)needtoexposeonlythecorrespondingbeanpropertiesorconstructorarguments(asyou’llseelaterinthischapter);theydonothavetoperformanycustomlookups.ArootwebapplicationcontextwillbeloadedbyaContextLoaderListenerthatisdefinedinweb.xmlasfollows:25 org.springframework.web.context.ContextLoaderListener...Afterinitializationofthewebapp,therootwebapplicationcontextwillbeavailableasaServletContextattributetothewholewebapplication,intheusualmanner.Itcanberetrievedfromthereeasilyviafetchingthecorrespondingattribute,orviaaconveniencemethodinorg.springframework.web.context.support.WebApplicationContextUtils.ThismeansthattheapplicationcontextwillbeavailableinanywebresourcewithaccesstotheServletContext,likeaServlet,Filter,JSP,orStrutsAction,asfollows:WebApplicationContextwac=WebApplicationContextUtils.getWebApplicationContext(servletContext);TheSpringwebMVCframeworkallowswebcontrollerstobedefinedasJavaBeansinchildapplicationcontexts,oneperdispatcherservlet.Suchcontrollerscanexpressdependenciesonbeansintherootapplicationcontextviasimplebeanreferences.Therefore,typicalSpringwebMVCapplicationsneverneedtoperformamanuallookupofanapplicationcontextorbeanfactory,ordoanyotherformoflookup.Neitherdootherclientobjectsthataremanagedbyanapplicationcontextthemselves:Theycanreceivecollaboratingobjectsasbeanreferences.TheCoreBeanFactory25 Intheprevioussection,wehaveseenatypicalusageoftheSpringIoCcontainerinawebenvironment:Theprovidedconvenienceclassesallowforseamlessintegrationwithouthavingtoworryaboutlow-levelcontainerdetails.Nevertheless,itdoeshelptolookattheinnerworkingstounderstandhowSpringmanagesthecontainer.Therefore,wewillnowlookattheSpringbeancontainerinmoredetail,startingatthelowestbuildingblock:thebeanfactory.Later,we’llcontinuewithresourcesetupanddetailsontheapplicationcontextconcept.Oneofthemainincentivesforalightweightcontaineristodispensewiththemultitudeofcustomfacto-riesandsingletonsoftenfoundinJ2EEapplications.TheSpringbeanfactoryprovidesoneconsistentwaytosetupanynumberofapplicationobjects,whethercoarse-grainedcomponentsorfine-grainedbusi-nessobjects.ApplyingreflectionandDependencyInjection,thebeanfactorycanhostcomponentsthatdonotneedtobeawareofSpringatall.HencewecallSpringanon-invasiveapplicationframework.FundamentalInterfacesThefundamentallightweightcontainerinterfaceisorg.springframework.beans.factory.BeanFactory.Thisisasimpleinterface,whichiseasytoimplementdirectlyintheunlikelycasethatnoneoftheimplementationsprovidedwithSpringsuffices.TheBeanFactoryinterfaceofferstwogetBean()methodsforlookingupbeaninstancesbyStringname,withtheoptiontocheckforarequiredtype(andthrowanexceptionifthereisatypemismatch).publicinterfaceBeanFactory{25 ObjectgetBean(Stringname)throwsBeansException;ObjectgetBean(Stringname,ClassrequiredType)throwsBeansException;booleancontainsBean(Stringname);booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;String[]getAliases(Stringname)throwsNoSuchBeanDefinitionException;}TheisSingleton()methodallowscallingcodetocheckwhetherthespecifiednamerepresentsasin-gletonorprototypebeandefinition.Inthecaseofasingletonbean,allcallstothegetBean()methodwillreturnthesameobjectinstance.Inthecaseofaprototypebean,eachcalltogetBean()returnsaninde-pendentobjectinstance,configuredidentically.ThegetAliases()methodwillreturnaliasnamesdefinedforthegivenbeanname,ifany.Thismecha-nismisusedtoprovidemoredescriptivealternativenamesforbeansthanarepermittedincertainbeanfactorystoragerepresentations,suchasXMLidattributes.ThemethodsinmostBeanFactoryimplementationsareawareofahierarchythattheimplementationmaybepartof.Ifabeanisnotfound25 inthecurrentfactory,theparentfactorywillbeasked,upuntiltherootfactory.Fromthepointofviewofacaller,allfactoriesinsuchahierarchywillappeartobemergedintoone.Beandefinitionsinancestorcontextsarevisibletodescendantcontexts,butnotthereverse.AllexceptionsthrownbytheBeanFactoryinterfaceandsub-interfacesextendorg.springframework.beans.BeansException,andareunchecked.Thisreflectsthefactthatlow-levelconfigurationprob-lemsarenotusuallyrecoverable:Hence,applicationdeveloperscanchoosetowritecodetorecoverfromsuchfailuresiftheywishto,butshouldnotbeforcedtowritecodeinthemajorityofcaseswhereconfig-urationfailureisfatal.MostimplementationsoftheBeanFactoryinterfacedonotmerelyprovidearegistryofobjectsbyname;theyproviderichsupportforconfiguringthoseobjectsusingIoC.Forexample,theymanagedependen-ciesbetweenmanagedobjects,aswellassimpleproperties.Inthenextsection,we’lllookathowsuchconfigurationcanbeexpressedinasimpleandintuitiveXMLstructure.Thesub-interfaceorg.springframework.beans.factory.ListableBeanFactorysupportslistingbeansinafactory.Itprovidesmethodstoretrievethenumberofbeansdefined,thenamesofallbeans,andthenamesofbeansthatareinstancesofagiventype:publicinterfaceListableBeanFactoryextendsBeanFactory{intgetBeanDefinitionCount();String[]getBeanDefinitionNames();String[]getBeanDefinitionNames(Classtype);25 booleancontainsBeanDefinition(Stringname);MapgetBeansOfType(Classtype,booleanincludePrototypes,booleanincludeFactoryBeans)throwsBeansException}TheabilitytoobtainsuchinformationabouttheobjectsmanagedbyaListableBeanFactorycanbeusedtoimplementobjectsthatworkwithasetofotherobjectsknownonlyatruntime.IncontrasttotheBeanFactoryinterface,themethodsinListableBeanFactoryapplytothecurrentfactoryinstanceanddonottakeaccountofahierarchythatthefactorymaybepartof.Theorg.springframework.beans.factory.BeanFactoryUtilsclassprovidesanalogousmethodsthattraverseanentirefactoryhierarchy.TherearevariouswaystoleverageaSpringbeanfactory,rangingfromsimplebeanconfigurationtoJ2EEresourceintegrationandAOPproxygeneration.Thebeanfactoryisthecentral,consistentwayofsettingupanykindofapplicationobjectsinSpring,whetherDAOs,businessobjects,orwebcontrollers.NotethatapplicationobjectsseldomneedtoworkwiththeBeanFactoryinterfacedirectly,butareusu-allyconfiguredandwiredbyafactorywithouttheneedforanySpring-specificcode.Forstandaloneusage,theSpringdistributionprovidesatinyspring-core.jarfilethatcanbeembed-dedinanykindofapplication.Itsonlythird-partydependencybeyondJ2SE1.3(plusJAXPforXMLparsing)istheJakartaCommonsLoggingAPI.ThebeanfactoryisthecoreofSpringandthefoundationformanyotherservicesthattheframeworkoffers.Nevertheless,thebeanfactorycaneasilybeusedstan-daloneifnootherSpringservicesarerequired.Derivative:network25 Spring框架简介Spring框架:这是一个流行的开源应用框架,它可以解决很多问题。这里主要介绍Spring的基本概念,并详细介绍其中以“bean工厂”为核心的轻量级控制反转(IoC)容器。Spring让开发者更轻松的实现轻量级、可扩展的J2EE架构。对于我们推荐的架构模块,让Spring提供了即时可用的实现。此外,Spring还提供了同意的应用架构方式,以及大量的中间层功能模块,能大大简化了J2EE的开发,并且比传统的开发方式更加灵活。第一章:Spring项目的出发点1.1解决被其它框架忽略的部分在J2EE的各个具体领域都有很多出色的解决方案----web框架、持久化方案、远程调用工具,凡此种种。然而,将这些工具整合成一个全面的架构却困难重重,甚至成为一种负担。Spring的目标就是提供一种贯穿始终的解决方案,将各种专用框架整合成一个连贯的整体架构。Spring还涉及到其它框架没有触及到的地方。例如,很少有框架提供普遍适用的事务管理或是数据库存储对象实现;即便各个领域都有很好的选择,也没有一个框架能够帮忙把所有这些东西整合到一个应用中去。因此,我们说Spring是一个应用框架,而不是web框架、IoC框架、AOP框架或者中间层框架什么的。1.2易于选择一个框架应该有清楚的层次划分,允许用户使用其中的单项功能,而不是把自己的整个世界观强加给用户。Spring中的许多特性---例如JDBC抽象层或者Hibernation集成----都可以作为一个库单独使用,当然也可以作为Spring整体方案的一个部分。1.3易于使用25 正如前面说过的,仅仅J2EE本身并不易用---很多常见的问题光靠J2EE都很难解决。一个好的基础框架首先应该让容易的任务容易完成,而不需要让应用开发人员现在就为将来的复杂需求(例如分布式事务)买单。框架应该帮助开发人员合理使用J2EE的服务(例如JTA),同时又避免造成对服务的依赖,从而减少不必要的复杂性。1.4鼓励最佳实现Spring力求把遵循最佳实践--例如“针对接口编程”--的成本降低到最小。另一方面,Spring又力求不强加任何架构风格,而是把选择的权利留给开发者。1.5非入侵性一个好的基础设施框架应保持应用组态灵活和一致,避免自定义单身和工厂的需要。一个单一的风格应该是适用于所有配置的需要,从中间层的网络控制器。1.6统一配置测试整个应用程序或单个应用程序类的单元测试应该尽可能的容易。模仿对象替换资源或应用程序的对象应该是简单的。1.7可扩展由于Spring本身是基于接口的,而不是类,它是很容易扩展或定制。许多Spring组件使某种形式的Strategy模式,因此可以方便定制。第二章:一个分层的应用框架前面我们从轻量级容器(lightwightcontainer)的角度介绍了Spring框架,并将其与别的IoC容器(例如PicoContainer)作了比较。虽然为JavaBean设计的轻量级容器是Spring的核心概念,但这也只是所有中间层解决方案的基础而已。2.1基础构建模块Spring是一个完整的应用框架,它可以在很懂应用层发挥作用。Spring由多个子框架组成,而且这些框架都是相对独立的。不过,只要你愿意,你就可以将它们无缝集成起来,成为一个全面的应用框架,下面讲解Spring框架的关键概念。2.1.1bean工厂Spring轻量级IoC容器能够配置、装备JavaBean和大多数Java对象,使得开发者不必定制Singleton和自己的配置机制。Spring提供了多个“即拿即用”25 的bean工厂实现。其中包括一个基于XML的bean工厂。轻量级IoC容器和依赖注入(DependencyInjcction)将是本章节关注的内容。2.1.2应用上下文Spring应用程序上下文添加消息来源和资源加载支持扩展bean工厂的概念,并提供钩到现有的环境中。不同的盒子的实现包括独立的应用程序上下文和基于Web的应用程序上下文的XML。2.1.3AOP框架Spring的AOP框架提供的任何类的Spring轻量级容器管理方法拦截AOP支持。可以对轻量级容器管理的任何对象进行方法拦截。在bean工厂中,可以轻松的为JavaBean提供代理,从而在运行天衣无缝地将拦截器和其他的adcice整合进来。我们将在后面详细讨论Spring的AOP框架。SpringAOP的主要用途就是为了POJO提供声明性的企业级服务。2.1.4自动代理Spring提供了一个更高的抽象层次的AOP框架和低水平的服务,同时也提供了很多基础性的服务,从而在J2EE环境中提供了类似于.NET的易用性--特别是,声明的企业提供的服务可以通过源代码级的元数据驱动的。2.1.5事务管理Spring提供了一个通用的交易管理基础设施,可插拔的交易策略(例如JTA和JDBC)和不同的事务划分方式。后面会详细介绍Spring事务管理的基本原理,及其强大的威力和灵活性。2.1.6DAO的抽象Spring定义一组通用的数据访问异常,在创建通用的DAO接口时可以用这些异常类型抛出有意义的异常信息,,独立于底层的存储机制。后面阐述了更多的细节讨论Spring对DAO的支持,以及针对JDBCJDO,Hibernate的不同实施策略。2.1.7JDBC的支持Spring提供了两个层次的抽象,使得编写基于JDBC的DAO特别简单:org.springframework.jdbc.core包提供了基于模板、回调的JDBC用法,org.springframework.jdbc.object包则把关系数据库操作建模为可服用对象。比起直接使用JDBC,用Spring的JDBC包可以提供更大的生产力和消除常见的错误,如泄漏等。SpringJDBC抽象层集成了事务抽象和DAO的抽象。2.1.8集成O/R映工具25 Spring提供了多种O/R映射工具的支持,如Hibernate,JDO和ibatis数据库简化资源设置,采集,和释放,并且将O/R映射与整个事务和DAO抽象集成起来。这些集成软件包允许应用程序分配自定义ThreadLocal会话和本地事务进行处理,不必考虑底层究竟采用哪种O/R映射工具。2.1.9webMVC框架Spring提供了一个相当干净的WebMVC实现--同样使用了统一JavaBean配置方式。使用Springweb框架时,web控制器也可以在IoC容器中配置,从而不必为“访问业务层服务”额外编写代码。Spring还提供了通用的DispatcherServlet和“即拿急用”的控制器类。请求与控制器之间的映射方式、师徒的判断、本地化、以及其他重要服务都是可以插的,使得整个框架酷友更好的扩展性。Springweb框架设计不仅仅局限于JSP,还可以与其他的视图技术--例如Velocity--无缝的结合。2.1.10远程调用支持Spring提供一种薄的抽象层用于访问远程服务,避免了在应用对象中硬编码对服务的查找。线成支持的远程调用方式包括RMI,Caucho的Hessian和BurlapWeb服务的协议,和基于JAX-RPCWSDL的Web服务。虽然Spring涉及了下至事务管理、上至webMVC的不同领域,它但它解决问题的方式却是一以贯之的。一旦你学会了基本的配置方式,你将能够应用在许多领域。资源,中间层对象,和Web组件都使用同一个bean配置机制的建立。你可以将你的整个配置在一个单一的bean定义文件或分裂,它的应用模块或层;选择是为应用程序开发人员到你。有没有需要在各种不同的格式,不同的配置文件,遍布的应用。第三章:J2EE之上的Spring虽然Spring的许多部分可用于任何Java环境,它主要是一个J2EE应用框架。例如,有链接到一个bean工厂的JNDI资源方便的类,如JDBC数据源和EJB和JTA,分布式事务管理一体化。在大多数情况下,应用程序对象不需要与j2eeapi直接,提高可重用性和意义,不需要写冗长,难以测试,JNDI查找。因此,Spring25 允许应用程序代码的无缝集成到J2EE环境不被不必要地捆绑在一起。你可以建立在J2EE服务,让您的应用程序,如果没有复杂的要求选择重量轻的解决方案。例如,你需要使用JTA事务的策略,如果你面对分布式事务的要求。为一个单一的数据库,有不依赖于一个J2EE容器替代策略。这些交易和策略之间的切换只是配置;春天的一致的抽象避免任何需要更改应用程序代码。Spring访问EJB提供支持。这是一个重要的特征(甚至在“没有EJB的J2EE一本有关)因为动态使用代理作为客户端业务代表无代码意味着春天可以使用本地的无状态会话EJB的实现程度,而不是一个根本的建筑,选择。因此,如果你想使用EJB,您可以在一个一致的架构;然而,你不需要让你的架构的基石,EJB。今年春天功能可以使开发EJB应用程序更快,因为不需要编写自定义代码在服务中心职责范围或业务代表。测试EJB客户端代码也容易得多,因为它不仅取决于EJB的业务方法接口(这是不特定的,不是在EJB)或EJBJNDIAPI。Spring也提供了实现EJB的支持,在方便的超类EJB实现类的形式,其中负载基于ejb-jar.xml部署描述符指定的环境变量的Spring轻量级容器。这是一个强大的和方便的方式实现SLSBs或MDBS是细粒度的POJO立面:最佳实践,如果你选择实现EJB应用。Spring的这些特性和EJB毫无冲突,因为它只是遵循了公认的最佳实践而已。Spring的主要目的是使J2EE更容易使用和促进良好的编程实践。Spring不重新发明轮子,这样你会在spring找不到登录包,连接池,分布式事务协调器。这些特征是由其他的开源项目,如JakartaCommons测井提供(Spring使用其所有的日志输出),JakartaCommonsDBCP(可作为局部数据源)和ObjectWebJOTM(可作为事务管理器)或通过你的J2EE应用服务器。出于同样的原因,Spring不提供O/R映射层:有良好的解决问题的方法,如Hibernate,JDO。Spring的目标是使现有的技术更容易使用。例如,虽然Spring不是低级事务协调业务,它提供了在jta或者任何交易策略的一个抽象层。Spring为Hibernate提供的中间层的基础设施也很受欢迎,因为它提供了像SessionFactory的设置,许多常见问题可以解决,ThreadLocal会议,与异常处理。与SpringHibernateTemplate类,HibernateDAO实现方法可以减少到一个衬垫,同时适当参与交易。25 Spring框架的目的并不是要取代J2EE中间层服务。这是一个应用程序框架,使访问低级J2EE容器服务更容易。此外,它提供了在某些情况下,某些J2EE服务的轻量级的替代品,如代替JTAJDBC基础交易策略时,只使用一个数据库。基本上,Spring将帮助你编写极具可伸缩性的应用程序。第四章:web应用中的Spring在J2EE环境中,Spring有一种典型的用法:为J2EEweb应用提供逻辑中间层的基本骨架。Spring提供了“web应用上下文”的概念,将一个强大的轻量级IoC容器无缝结合到web环境中,各种web层程序--不管是Struts、webWork、JSF、SpringwebMVC还是其他自制的方案--都可以使用IoC容器。下面的代码显示了这样一个Web应用程序上下文的一个典型的例子。在一个典型的Springweb应用中,applicationContext.xml文件驻留在WEB-INF目录,包含bean的声明(遵循“spring-beans”DTD)。这个文件中定义了业务对象和资源对象,如“myDataSource”、“myInventoryManager”和“myProductManager”等。Spring将负责管理所有这些bean的配置、关联和生命周期。com.mysql.jdbc.Driverjdbc:mysql:mydstrue25 在默认情况下,所有的bean都是通过Singleton模式创建的:每个应用上下文中只有一个实例。当Spring开始构造上述应用上下文时,“myInventoryManager”bean将自动获得生命的DataSource对象(“myDataSource”bean):随后,“myProductManager”也会获得“myInventoryMnager”bean的引用。这些对象(也就是Spring属于常说的“bean”)只需要暴露相应的bean属性或者后遭子参数即可,而不需要进行任何特定的查找操作。我们在web.xml中定义一个监听器(ContextLoaderListener),用于加载根应用上下文(rootapplicatiobcontext)。这个监听器定义如下:org.springframework.web.context.ContextLoaderListener...Web应用程序的初始化后,根Web应用程序上下文将作为ServletContext的属性对整个Web应用程序,以通常的方式。它可以很容易地通过取相应的属性,从那里检索,或通过org.springframework.web便利的方法。context.support.webapplicationcontextutils。这意味着应用程序的上下文将在任何Web资源访问ServletContext可用,如Servlet,JSP,过滤器,或Struts动作,如下:WebApplicationContextWAC=webapplicationcontextutils。getwebapplicationcontext(ServletContext);SpringWeb25 MVC框架允许web控制器被定义为在应用程序上下文中的孩子,每一个调度servlet。这种控制器可以表达依赖于豆类中的根的应用程序上下文中通过简单的bean的引用。因此,典型的SpringWebMVC应用程序不需要执行一个应用程序上下文或bean工厂手工查找,或做任何其他形式的查找。其他客户端对象是由应用程序上下文自己管理不:他们可以接收的协作对象作为bean的引用。第五章:核心bean工厂在前面的章节中,我们已经看到在一个网络环境的SpringIoC容器典型用途:提供便利类允许无缝集成,而不必担心底层容器的细节。然而,它确实帮助的内部运作看明白春天经营集装箱。因此,现在我们将看看更详细的Springbean容器,从最低的建筑块:bean工厂。后来,我们将继续在应用程序上下文的概念资源设置和细节。一个轻量级容器的主要动机之一是用定制的工厂,经常发现在J2EE应用程序的许多单身。Springbean工厂提供了设置任何数量的应用程序对象的一个一致的方式,无论是粗粒度组件或细粒度业务对象。应用反射和依赖注入,bean工厂可以不需要知道Spring所有的组件的宿主。因此,我们称之为Spring的一种非侵入性的应用程序框架。第六章:基础接口在Spring中,轻量级容器最基本的接口时org.springframework.beans.facory.BeanFactory。这是一个非常简单的接口,所以如果没有任何现成的bean工厂实现能够满足你的要求(这种情况非常罕见)。你也可以很容易地创建自己的实现。BeanFactory接口提供了两个getBean()方法,它们都可以根据String类型的名称查找获取bean实例,两者的不同之处在于:其中一个getBean()方法允许使用者检查获得的bean是否具有所需的类型(如果类型不符,会抛出一个BeanNotOfRequireTypeExpection异常)。publicinterfaceBeanFactory{ObjectgetBean(Stringname)throwsBeansException;ObjectgetBean(Stringname,ClassrequiredType)throws25 BeansException;booleancontainsBean(Stringname);booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;String[]getAliases(Stringname)throwsNoSuchBeanDefinitionException;}使用者可以通过issingleton()方法检查牧歌特定名称声明的bean被定为Singleton还是Prototype。如果bean被定义为Singleton,所有对getBean()方法的调用将返回同一个对象实例的引用;如果bean被定义为Prototype,每次对getBean()的调用都将新建一个独立的对象实例。如果某个bean配置了别名,getAliases()方法将返回它所有的别名。借助这种机制,我们可以为bean提供更具描述力的名称,而不必受特定的bean工厂存储机制的约束--例如XML文档对id属性的取值就有诸多限制。在大多数的BeanFactory实现方法是意识到一个层次,可实施的一部分。如果一个bean是不是在目前厂发现,母厂会问,直到根厂。从一个人的角度,在这样一个层次结构的所有工厂会合并成一个。在祖先的上下文的bean定义中是可见的后代,而不是反。BeanFactory接口的大多数实现不仅提供给了一个可以按名称查询的对象注册表,对于“用IoC配置这些对象”也提供了丰富的支持。例如,他们可以管理对象之间的依赖关系,也可以将简单属性值赋给对象。在下一节,我们将看到如何在一个简单、直观的XML结构中描述这些配置信息。25 大多数的BeanFactory接口实现不只是提供一个注册的对象的名称;他们提供配置这些对象使用IOC丰富的支持。例如,他们管理的托管对象之间的关联,以及简单的性质。在下一节,我们将看看这样的配置可以在一个简单而直观的XML结构表达。Org.springframework.beans.factory.listablebeanfactory子接口可以列出工厂中所有的bean。这个子接口提供了一系列方法,可以用于获得工厂中定义bean的数量、所有bean的名称、具有特定类型的所有的名称等:publicinterfaceListableBeanFactoryextendsBeanFactory{intgetBeanDefinitionCount();String[]getBeanDefinitionNames();String[]getBeanDefinitionNames(Classtype);booleancontainsBeanDefinition(Stringname);MapgetBeansOfType(Classtype,booleanincludePrototypes,booleanincludeFactoryBeans)throwsBeansException}ListableBeanFactory可以获得管理对象的相关信息,可以利用这一能力来实现这样的对象:这种对象需要与一组别的对象协作,并且只有到运行时才知道与其协作的究竟是哪些对象。相反,BeanFactory接口,在ListableBeanFactory方法适用于目前的工厂实例和不带一个层次的帐户,工厂可能是部分。该org.springframework.beans.factory.beanfactoryutils类提供了类似的方法,遍历整个工厂层次。Spring的bean工厂有很多种方法,从简单的bean配置J2EE资源整合和AOP代理生成。bean工厂是中央的,一致的方式设置任何一种在春天,应用对象是否刀,业务对象,或网络控制器。注意,应用对象很好需要直接用到BeanFactory接口--它们通常都在工厂中配置、组装,不需要针对Spring编写任何特殊的代码。如果只需要使用bean工厂,Spring发布了一个很小的spring-core.jar文件,可以植入任何种类的应用中去。除了J2SE1.3(以及用于XML解析的JAXP)之外,它唯一依赖的第三方只有JakartaCommonsLoggingAPI。25 出处:网络25

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

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

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