Tải bản đầy đủ

Apress enterprise javabeans 2 1 apr 2003 ISBN 1590590880

EnterpriseJavaBeans2.1
byStefanDenninger,Ingo
PetersandRobCastenada
Apress©2003

ISBN:1590590880

Thisinvaluableresourcedetailsthe
architectureoftheEnterpriseJavaBeans
componentmodelandtheJavaMessage
Service(JMS)soyouunderstandtheideas
behindasynchronousandparallelprocessing
providedthroughmessage-drivenbeans.
TableofContents
EnterpriseJavaBeans2.1
Preface
Chapter1 - Introduction
Chapter2 - Fundamentals
Chapter3 - TheArchitectureofEnterpriseJavaBeans
Chapter4 - SessionBeans
Chapter5 - EntityBeans

Chapter6 - Message-DrivenBeans
Chapter7 - Transactions
Chapter8 - Security
Chapter9 - PracticalApplications
Chapter10 - WebServicesandScheduling
References
Index
ListofFigures
ListofTables


ListofListings


BackCover
EnterpriseJavaBeans(EJB)isaserver-sidecomponent
modelfortransaction-awaredistributedenterprise
applications,writtenintheJavaprogramming
language.EnterpriseJavaBeans2.1detailsthe
architectureoftheEnterpriseJavaBeanscomponent
model.
Aftertheauthorsintroducethecomponentparadigm,
theymoveontocoverEJBarchitecturebasics.Building
onthefoundationformedinthoseintroductorytopics,
theydiscussthedifferentcomponenttypes(session-,
entity-,andmessage-drivenbeans)indetail.Thisis
followedbyacomprehensiveintroductiontotheJava
MessageService(JMS),soyouunderstandtheideas
behindasynchronousandparallelprocessingprovided
throughmessage-drivenbeans.Transactions,security,
andthenewlyintroducedtimerserviceroundoutthe
book.
Thisinvaluableresourcealsodiscussestopicsbeyond
thespecification:inheritance,couplingofEJB
components,qualityassurance,andmore.After
readingthisbook,you'llunderstandthebenefitsand
thelimitsofEJBandhavetheknowledgenecessaryto
turnbusinessrequirementsintoEJB-based
applications.
AbouttheAuthors


StefanDenningercompletedhisuniversityeducationin
February1996withadegreeinbusinessmanagement.
HecurrentlyworksforConSolGmbHinMunichasa


seniorsoftwareconsultant.Hehasworkedasa
softwareengineerforKromberg&Schubertin
Abensberg,Germany,IXOSSoftwareinMunich,
Germany,andeCircleSolutionsinMunich.
IngoPeterscurrentlyworkswiththeHypoVereinsbank,
agroupofEuropeanbanksmanagingInternetportals
andapplications.Asaprojectmanager,hehasguided
manydifferentapplicationsandInternetportalsusing
EnterpriseJavaBeanstosuccess.Hestarted
programmingwithEnterpriseJavaBeansin1998.
RobCastanedaisPrincipalArchitectatCustomWare
AsiaPacific,whereheprovidesarchitectureconsulting
andtraininginEJB/J2EE/XML-basedapplicationsand
integrationserverstoclientsthroughoutAsiaand
America.Rob’smultinationalbackground,combined
withhisstrongreal-worldbusinessexperience,enables
himtoseethroughthespecificationstocreaterealistic
solutionstomajorbusinessproblems.Hehasalso
contributedtoandtechnicallyeditedvariousleading
EJBandJ2EEbooks.


EnterpriseJavaBeans2.1
STEFANDENNINGERand
INGOPETERSwith
ROBCASTANEDA
translatedbyDavidKramer

Copyright©2003byStefanDenningerandIngoPeterswithRob
Castaneda
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-088-0
PrintedandboundintheUnitedStatesofAmerica12345678910
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
Translator,Editor,Compositor:DavidKramer
TechnicalReviewer:MarySchladenhauffen
EditorialDirectors:DanAppleman,GaryCornell,SimonHayes,Martin
Streicher,KarenWatterson,JohnZukowski
ManagingandProductionEditor:GraceWong
Proofreader:LoriBring
CoverDesigner:KurtKrames


ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany
IntheUnitedStates,phone1-800-SPRINGER,email
,orvisithttp://www.springerny.com
OutsidetheUnitedStates,fax+496221345229email
,orvisithttp://www.springer.de,
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax:
510-549-5939,email,orvisit
http://www.apress.com.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
http://www.apress.comintheDownloadssection.
AbouttheAuthors
StefanDenninger
StefanDenningercompletedhisuniversityeducationinFebruary1996
withadegreeinbusinessmanagement.Hehasworkedasasoftware
engineerforKromberg&SchubertinAbensberg,Germany,IXOS
SoftwareinMunich,Germany,andeCircleSolutionsinMunich.He
currentlyworksforConSolGmbHinMunichasaseniorsoftware
consultant.


IngoPeters
IngoPeterscurrentlyworkswiththeHypoVereinsbank,agroupof
EuropeanbanksmanagingInternetportalsandapplications.Asaproject
manager,hehasguidedmanydifferentapplicationsandInternetportals
usingEnterpriseJavaBeanstosuccess.Hestartedprogrammingwith
EnterpriseJavaBeansin1998.
RobCastaneda
RobCastanedaisPrincipalArchitectatCustomWareAsiaPacific,where
heprovidesarchitectureconsultingandtraininginEJB/J2EE/XML-based
applicationsandintegrationserverstoclientsthroughoutAsiaand
America.Rob'smultinationalbackground,combinedwithhisstrongrealworldbusinessexperience,enableshimtoseethroughthespecifications
tocreaterealisticsolutionstomajorbusinessproblems.Hehasalso
contributedtoandtechnicallyeditedvariousleadingEJBandJ2EE
books.
Acknowledgments
Workingonthisbookhasbeenagreatpleasureforalloftheauthors.
Longdiscussionsaboutlocalinterfacesanddependentobjectshave
resultedinseveralchaptersbeingrewrittenandthenrewrittenagain,and
changesinthespecificationhaveledtomanyinterestingdiscussionsand
insights.
Withouttheactivesupportofcolleaguesandfriends,workonthisbook
wouldnothavebeennearlysointeresting,norsoproductive.Stefan
DenningerandIngoPeterswouldlikeparticularlytothankStefan
SchulzeandAlexanderGreisle,whoseconstructiveandhighly
competentfeedbackhavesignificantlyimprovedthequalityofthisbook.
TheywouldalsoliketothankthereadersofthefirstGermanedition,
whosesupportandfeedbackmadethesecondeditionpossible.Finally,
theywishtothanktheireditor,MartinAsbach,ofAddison-Wesley,forhis
greatcareandfriendlycollaborationinbringingthisbookintotheworld,
tothestaffofApressformakingtheEnglishtranslationpossible,andfor
theiramiableanduncomplicatedcollaboration.


RobCastanedawouldliketothankJohnZukowski,GraceWong,andthe
teamatApress,aswellascolleaguesatCustomWareAsiaPacific,
includingIanDaniel,NathanLee,andScottBabbage,aswellashiswife,
AimeeCastaneda.Withoutthesupportofthetheseindividuals,thiswork
wouldnothavebeenachievable.


Preface
EnterpriseJavabeans(EJB)isthestandardcomponentarchitecturefor
thecreationofdistributedbusinessapplicationsintheprogramming
languageJava.EJBoffersallmechanismsnecessaryforthecreationof
applicationsforenterprise-widedeploymentandforthecontrolofcritical
businessprocesses.Applicationdeveloperscanprofitfromdistributionof
processes,transactionsecurity,poolingofnetworkconnections,
synchronousandasynchronousnotification,multithreading,object
persistence,andplatformindependence.WithEJB,programming
remainsrelativelysimple.
InMarch1998thefirstspecificationofEnterpriseJavaBeanswas
publishedbySunMicrosystems.Inrelativelyshortordertherefollowedin
December1999theconsolidatedversion1.1.Inthemeantime,the
componentarchitecturehasaccountedforconsiderablechangeinthe
marketforapplicationservers,sothattoday,thelargemajorityof
applicationserverssupportEJB.EJBhasalsoestablisheditselfinthe
growingmarketforfinishedapplicationcomponents.Today,thereexistsa
largemarketforeverythingfromspecializedsolutionstospecific
problemstocompleteapplicationframeworks.
InAugust2001version2.0wasreleased.Thenewversionoffers
considerableextensionsandimprovements,whichareconsideredinthis
book,nowinitssecondedition.Thefirsteditionhasbeengreatlyrevised
inordertotakeaccountofthefollowingdevelopments:
Thenewmessage-drivenbeans(EJB2.0)offercompletelynew
waystoachieveasynchronouscommunicationandparallel
processingofbusinesslogic.Thisismadepossiblebythe
integrationoftheJavaMessageService(JMS)intothtEJB
architecture.
Localinterfaces(EJB2.0)enableoptimizationofprocess-internal
communicationamongEnterpriseBeansandbetweenlocal
clientsandEnterpriseBeans.
Thepersistencemanagerhasbeenintroduced(EJB2.0).With


relationshipsbetweenentitybeansitisnowpossibletomodel
complexdatastructures.TheassociatedquerylanguageEJBQL
makesitpossibletoworkefficientlywiththesestructures.
Anewchapter(Chapter8)dealswithsecurityissuesofEJB.
Thechapteronpracticalapplications(Chapter9)hasbeen
greatlyexpanded.
Alltheexampleshavebeenreworked,withemphasisoneaseof
execution.
Today,onemaysafelystatethatEnterpriseJavaBeanshasbroughtthe
successoftheprogramminglanguageJavatotheserver,particularlyin
theareasofportalsandintegrationofolderapplications,whereEJBhas
becomeawidelyusedsolutionstrategy.However,informationtechnology
isonthevergeofyetnewchanges.Thetrendtodayisinthedirectionof
freelycombinableapplicationcomponentsfromavarietyofproducers
thatareconnectedviawebservices.EJB2.0offersanswerstothese
growingrequirements.Particularlythenewdevelopmentsintheareasof
marketplaces,privatestockexchanges,e-procurement,andelectronic
fundstransfercanprofitfromusingEJBasthebasearchitecture.
Thisbookisdirectedtothereaderwhowishestolearnmoreabout
EnterpriseJavaBeans.Itdiscussesthefundamentalconceptsunderlying
theEJBarchitecture.Buildingonthisfoundation,itexplainsthetechnical
detailsandconcreteprogrammingofEnterpriseBeans.Manyexamples
areusedtoclarifyandexpandontheconceptsintroduced.Thesource
codeforalltheexamplesinthisbookisavailableat
http://www.apress.cominthe"Downloads"section.Aknowledgeof
theJavaprogramminglanguageandabasicunderstandingofdistributed
programmingareprerequisitesforreadingthisbook.


Chapter1:Introduction


AHypotheticalScenario
Imaginethatyouareanapplicationprogrammerworkingforamidsize
firmintheautomobileindustrythatmaintainsnumerousofficesina
numberofEuropeancountries.Yourfirmispursuingthestrategyof
developingitsownbusinessapplicationsinhouse.Atfirstglancesucha
strategymayseemratherodd.Butextremecompetitionandincreasing
costpressuresnowdemandahighlevelofflexibilityandstabilityfromthe
developmentteam,andyourdivisionleaderhasguaranteedthatthe
softwaresystemsdevelopedwillhavethesecharacteristics,andthisis
thejustificationformanagement'sdecisiontosupportin-house
development.
Uptonoweachofficehasinstalledandmaintaineditsownsoftware
system,sincethedevelopmentteamsineachbranchhavebeenworking
independentlyofoneanother.


FirsttheBadNews
Onefineday,youaresummonedtoyourdivisionleader'soffice.He
informsyouthatbigeventsareabouttooccurinthedataprocessing
divisionofthecompany.Toaccommodateincreasinginternationalgrowth
andtopromoteefficiency,allthesoftwareintheentirecompanyistobe
unified,standardized,andstreamlinedintoasingledistributedsystem.
Thedevelopmentteamswillremainattheindividualoffices,but
beginningatoncetheyarealltoreporttoanewlyappointeddivision
leader,underwhosedirectiontheyaretoworktogethertoachievethe
statedgoals.Existingsoftwareattheindividualbranchofficesistobe
replacedpiecebypiecebythenewlydevelopedreplacementpackages.
Isolatedsystemsinvariouspartsofthecompany(suchaspersonnel
managementandaccounting)aretobeintegratedintothenewsystem.
Thusyou,aspecialistinaccountingandsupplysystems,areaffectedby
thenewdevelopments.


TheTask
Yourjobistodevelopaprototypeforthisnewsystem,whichafteran
evaluationphaseistobefurtherdevelopedintoastablebuildingblockof
thenewsystem.Yourpieceoftheactionistobearudimentary
accountingsystem.Otherofficesaretodevelopcompatibleinventoryand
annualaccountsmodules,andtheytogetherwithyouraccounting
modulearetobepresentedtocompanymanagement.Anumberofusers
fromthevariousdivisionsmustbeabletousethesystemsimultaneously.
Sinceyourcompanyisplanningonintroducingtelecommuting,the
systemmustalsobeusablefromoutsidethecompany,overtheInternet,
forexample.Inordertoavoidbottlenecksduringcriticalperiods(suchas
theendofaquarteroryear)thesystemmustbeabletooperateunder
heavyusage.Furthermore,anticipatedgrowthinthenumberof
employeesmustalsobetakenintoaccount.


TheSolution
Asuperficialreadingoftheabovetextcouldeasilyleadonetothe
conclusionthatthetaskassetoutshouldgivelittletroubletoan
applicationdeveloperwhoisanexpertinbusinessapplications.Butif
onereadsmoreclosely,arathermorecomplexpicturebeginstopresent
itself(seeFigure1-1).Thecruxoftheproblemisinthenewsetof
circumstancesthatconfrontourapplicationspecialist.Thesealtered
circumstancesbringproblemsthatwillcomplicatethedevelopmentofa
prototypeofarudimentaryaccountingsystem.Letusexaminethe
situationmorecloselyintermsofthefollowingobservations.


Figure1-1:Solutionofabusinessproblem.


Multiple-UserCapability
Theaccountingsystem,whichuntilnowhasbeenconceivedasan
isolatedsolution,mustnowbeintegratedintoalargersystemandenable
anumberofuserstoworksimultaneously.Forthisthesystemmust
satisfythefollowingrequirements:
multiprocesscapability(multithreading),
transactions,
usercontrol,
securitymechanisms,
networkingcapability.
Afurtherconsiderationisthenecessityofensuringthattherequirements
listedabovearestandardizedandconsistentamongallmodulesofthe
system.Thisisaveryimportantrequirementtoconsider.Itisoften
overlookedbecauseitdoesnotdirectlymaptoanyuserrequirements,
anditbecomesacriticalfactorinworkingwithremotedevelopment
teams.


Scalability
Toaccommodateanincreaseinthenumberofemployeesthesystem
mustbescalable.Ifthepreviouslyavailableresourcesbecome
overtaxed,thenitmustbepossibletoexpandthesoftwaretoinclude
additionalresources.Thisgoalresultsinadistributionoftheapplications
amongseveralserversusuallylocatedwithinacluster.Thesystem
shouldthen(possiblyafterareconfiguration)makeuseofthenew
resourcesandthusofferimprovedperformancewithouttheoccurrenceof
bottlenecks.Itisimportantthatthereconfigurationandredeploymentof
anapplicationbeflexibleandnotrequiremajorsourcecode
modificationsandrecompilation.Rigiddesignsthatrequirethatsource
codemodificationsbemadeinreconfiguringandredeployingthesystem
reducethesystem'sflexibilityandincreasetheburdenonthesystem
administrator.


Availability
Ingeneral,butmostimportantlyatcriticaljuncturessuchasendof
quarteroryearend,thesystemmustofferahighdegreeofavailability.If
acomputerbecomesunavailable,thenanothercomputermustbeableto
takeovertherequisitefunctionswithoutagreatdealofeffort(orperhaps
noneatall)inreconfiguringthesystem.Thisrequiresthatthesystembe
capableoftransferringfunctionalunitsfromonecomputertoanother.


ConnectionwiththeOutsideWorld
Sincethecompanyhopestoworkwithgreatercooperationamongits
associatedpartsandalsoplansonintroducingtelecommuting,the
systemmustofferaninterfacetotheoutsideworld(forexample,through
adefinedportthroughthecorporatefirewall).Theresultisnotonlyan
increaseinsecurityrequirements,butalsointherequirementsonthe
systemarchitectureingeneral,sincethestructureofInternetapplications
isfundamentallydifferentfromthatoftraditionalapplications.


IntegrationwithOtherApplicationsandRapid
Extensibility
Intheidealcasethemethodofintegrationissuchthatvarious
applicationsthathavebeendevelopedasacollectionofbuildingblocks
canbeassembledintoacompletesystem.Eachapplicationshoulditself
beconstructedofbuildingblocksandhavethecapacitytomakeitself
availabletootherapplicationsinalimitedwaybymeansofclearly
definedinterfaces.Thesystemcanbeextendedthroughtheprovisionof
additionalbuildingblocks.Thismeansthatthebasicstructureofthe
systemsupportsasuitabledegreeofgranularity.


ShortDevelopmentCycles
Inthesoftwaredevelopmentprocesstherequirementofefficiencyplaces
onefundamentalgoalintheforeground:shorteningthedevelopment
cycleandtherebyreducingdevelopmentcosts.Thechallengeforthe
developmentteamistoreducedevelopmentcosts,whilemaintaining(or
evenimproving!)thequalityandrobustnessofthesystem.Thisis
achieved,asarule,throughincreasingthegranularity.Legacy
applicationscanalsobeaddedintothesystembythecreationofbuilding
blocksthatwrapperexistingfunctionality.Alargeandunwieldyprojectis
subdividedintomanysmall,easilymanagedprojects,eachofwhich
constitutesabuildingblock.Thetotalityofallthebuildingblocksisthe
system.Eachbuildingblockcanbedefined,built,andtestedasan
individualpieceoffunctionalitytoensurequality.Thusthisbuilding-block
approachcontributesnotonlytointegrabilityandextensibility,buttothe
shorteningofthedevelopmentcycleaswell.Italsohelpstoprovidefor
remotedevelopment,sincebuildingblockscanbedesignedandthen
developedatremoteofficesandintegratedoncecompletedforend-toendtesting.


Configurability
Ifapplicationsthataredevelopedinonelocationaretobeusableat
another(justthinkofdifferencesinnationallaws,languages,notation,
andonandon),thentheremustbeahighdegreeofconfigurability,so
thattheapplicationscanbeadaptedwithoutthenecessityofbeing
recompiled.Asafurtheralternativeonemightimagine(thinkingagainof
thebuilding-blockapproach)replacingbuildingblocksthatcannotbe
implementedataparticularlocationbylocation-optimizedbuilding
blocks.


StepwiseMigrationandDataStorage
Rome,ashasoftenbeenobserved,wasnotbuiltinaday(anditisstill
underconstruction!),andneithercanasystemredesignand
reconfigurationtakeplaceovernight.Therefore,thestep-by-step
changeovertoanewsystemisanimportanttopic.Itshouldbesimpleto
createinterfacestoexistingsystems,arequirementthatresultsin
somethingevenmoreimportant:Intheidealcaseitshouldmakeno
differencetoaparticularapplicationwheredataisstored.Itcanbe
locatedinadatabasebelongingtothenewsystem,inadatabase
belongingtoanoldsystem,orindeedinanexternaldatabasethatdoes
notbelongtothesystematall.


Summary
Thenumberofconsiderationsthatarerequiredinordertoproducethe
solutiontoourproblemcaneasilyexceedthecapabilitiesofanormally
endowedapplicationdeveloper.However,todayanumberofsoftware
companiesoffersolutionstodevelopersthatprovidewaysofovercoming
theproblemsinherentinaprojectsuchastheonethatwehave
described,andagreatdealofthethoughtanddesignrequiredtohandle
theissueslistedabovehavebeencollectedintoanumberofindustry
standardplatforms.Thisbookdiscussesoneoftheseplatformsingreat
detail:EnterpriseJavaBeans(orEJBforshort).Sowakeupandsmell
thecoffee,andlet'sgetstarted.


SoNowWhat?
InChapter2wediscussthefundamentalsofEnterpriseJavaBeansand
placetheminthecontextofthetechnologiesforsoftwaredevelopment.
InChapter3wedevoteourattentiontothefundamentalarchitectureof
EnterpriseJavaBeansaswellastherolesthatthedevelopmentteam
canplayduringthedevelopment,deployment,andmanagementstages
ofthesystem.Thedifferentvarietiesofcomponents(knownasbeans),
namely,entity,session,andmessage-drivenbeans,arediscussedin
Chapters4,5,and6.BuildingonthiswegooninChapter7todiscuss
thetopicoftransactions,whileChapter8isdevotedtosecurity.Ineach
ofthesechaptersextensiveexamplesareintroducedtoclarifythe
discussion.InChapter9wediscussseveralaspectsofthepractical
applicationoftheprinciplesdiscussed(againwithextensiveexamples).
Finally,inChapter10,wediscusswebservicesandtheintegrationof
EnterpriseJavaBeanstootherplatformsthatexistwithincommon
enterprises.
Afteryouhavereadthisbookyoushouldhaveafirmgraspofthe
capabilitiesoftheEnterpriseJavaBeansplatform.Furthermore,you
shouldbeinapositiontotranslatetheknowledgeyouhavegainedfrom
theoryintopractice.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×