Tải bản đầy đủ - 0 (trang)
Chapter 2. Setting Up a Project Using Maven 2

Chapter 2. Setting Up a Project Using Maven 2

Tải bản đầy đủ - 0trang

AdvancedArchetypes

UsingAssemblies



2.1.MavenandtheDevelopmentBuild

Process

Inthischapter,welookatthesecondmajorplayerintheJava

buildtoolsarena:Maven.[*]Mavenisanincreasinglypopular

opensourcebuildmanagementtoolforenterpriseJava

projects,designedtotakemuchofthehardworkoutofthe

buildprocess.Mavenusesadeclarativeapproach,inwhichthe

projectstructureandcontentsaredescribed,ratherthenthe

task-basedapproachusedinAntorintraditionalMakefilesor

shellscripts.Mavenalsostronglypromotestheuseofstandard

directorystructuresandawell-definedbuildlifecycle.Thishelps

enforcecompany-widedevelopmentstandardsandreducesthe

timeneededtowriteandmaintainbuildscripts.

[*]Inthisbook,wewillbefocusingexclusivelyonthemostrecentversionof



Maven,Maven2,whichisradicallydifferentfromitspredecessor,Maven1.



Maven'sauthorsdescribeMavenasa"projectmanagement

framework,"anditisindeedmuchmorethanjustasimple

buildscriptingtool.Maven'sdeclarative,standards-based

approachtoprojectbuildmanagementsimplifiesmanyaspects

oftheprojectlifecycle.Aswellascateringforcompiling,

building,testing,anddeployingyourapplicationwitha

minimumofeffort,Mavenoffersanumberofotherkey

advantages:

Projectdependenciesaredeclaredandmanagedinaclean,

transparentway,whichreducestheriskofdependencyrelatederrorsandmakesforbetterdocumentation.

Mavenletsyoueasilygenerateuseful,high-quality,

technicaldocumentationandreportsaboutthecurrentstate

oftheprojectandprojectteammembers.Notethatwe

aren'ttakingaboutagoodusermanual,whichisan



altogetherdifferentissue,but,rather,abouttechnical

documentation,writtenbydevelopersfordevelopers.In

manytechnicalprojects,decenttechnicaldocumentationis

woefullyinadequate.Itisneverthelessavitalpartof

modernsoftwaredevelopment,especiallywhendislocated

teamsareinvolved.

Mavenproposesaclearstandarddirectorylayoutforsource

code,projectresourcesandconfigurationfiles,generated

output,andprojectdocumentation.Thismakesiteasierto

understandnewMavenprojects,andalsomakestheMaven

buildscriptscleanerandsimpler.

Mavenintegratessmoothlywithsourcecoderepositories,

continuousintegrationservers,andissuetrackingsystems.

TheMavenbuildcycleisflexible:itiseasytointegrate

additionalbuildtasks,usingexistingMavenplug-insorby

writingAntscriptlets.

AllofthesepointsmakeMavenaninvaluabletoolforJava

developmentteams.Indeed,Maventouchessomanypartsof

theSDLCthatthisbookcontainstwodistinctchaptersonthe

subject.Inthischapter,wewilllookatthebasicsofusing

Mavenintherealworld.InChapter29,wewillfocusonhowto

generateatechnicalwebsiteforyourprojectusingMaven.



Chapter2.SettingUpaProjectUsing

Maven2

MavenandtheDevelopmentBuildProcess

MavenandAnt

InstallingMaven

DeclarativeBuildsandtheMavenProjectObjectModel

UnderstandingtheMaven2Lifecycle

TheMavenDirectoryStructure

ConfiguringMaventoYourEnvironment

DependencyManagementinMaven2

LookingforDependencieswithMvnRepository

ProjectInheritanceandAggregation

CreatingaProjectTemplatewithArchetypes

CompilingCode

TestingYourCode

PackagingandDeployingYourApplication

DeployinganApplicationUsingCargo

UsingMaveninEclipse

UsingMaveninNetBeans

UsingPlug-InstoCustomizetheBuildProcess

SettingUpanEnterpriseRepositorywithArchiva

SettingUpanEnterpriseRepositoryUsingArtifactory

UsingAntinMaven



AdvancedArchetypes

UsingAssemblies



2.1.MavenandtheDevelopmentBuild

Process

Inthischapter,welookatthesecondmajorplayerintheJava

buildtoolsarena:Maven.[*]Mavenisanincreasinglypopular

opensourcebuildmanagementtoolforenterpriseJava

projects,designedtotakemuchofthehardworkoutofthe

buildprocess.Mavenusesadeclarativeapproach,inwhichthe

projectstructureandcontentsaredescribed,ratherthenthe

task-basedapproachusedinAntorintraditionalMakefilesor

shellscripts.Mavenalsostronglypromotestheuseofstandard

directorystructuresandawell-definedbuildlifecycle.Thishelps

enforcecompany-widedevelopmentstandardsandreducesthe

timeneededtowriteandmaintainbuildscripts.

[*]Inthisbook,wewillbefocusingexclusivelyonthemostrecentversionof



Maven,Maven2,whichisradicallydifferentfromitspredecessor,Maven1.



Maven'sauthorsdescribeMavenasa"projectmanagement

framework,"anditisindeedmuchmorethanjustasimple

buildscriptingtool.Maven'sdeclarative,standards-based

approachtoprojectbuildmanagementsimplifiesmanyaspects

oftheprojectlifecycle.Aswellascateringforcompiling,

building,testing,anddeployingyourapplicationwitha

minimumofeffort,Mavenoffersanumberofotherkey

advantages:

Projectdependenciesaredeclaredandmanagedinaclean,

transparentway,whichreducestheriskofdependencyrelatederrorsandmakesforbetterdocumentation.

Mavenletsyoueasilygenerateuseful,high-quality,

technicaldocumentationandreportsaboutthecurrentstate

oftheprojectandprojectteammembers.Notethatwe

aren'ttakingaboutagoodusermanual,whichisan



altogetherdifferentissue,but,rather,abouttechnical

documentation,writtenbydevelopersfordevelopers.In

manytechnicalprojects,decenttechnicaldocumentationis

woefullyinadequate.Itisneverthelessavitalpartof

modernsoftwaredevelopment,especiallywhendislocated

teamsareinvolved.

Mavenproposesaclearstandarddirectorylayoutforsource

code,projectresourcesandconfigurationfiles,generated

output,andprojectdocumentation.Thismakesiteasierto

understandnewMavenprojects,andalsomakestheMaven

buildscriptscleanerandsimpler.

Mavenintegratessmoothlywithsourcecoderepositories,

continuousintegrationservers,andissuetrackingsystems.

TheMavenbuildcycleisflexible:itiseasytointegrate

additionalbuildtasks,usingexistingMavenplug-insorby

writingAntscriptlets.

AllofthesepointsmakeMavenaninvaluabletoolforJava

developmentteams.Indeed,Maventouchessomanypartsof

theSDLCthatthisbookcontainstwodistinctchaptersonthe

subject.Inthischapter,wewilllookatthebasicsofusing

Mavenintherealworld.InChapter29,wewillfocusonhowto

generateatechnicalwebsiteforyourprojectusingMaven.



2.2.MavenandAnt

Withoutadoubt,themostpopularandmostwell-knownbuild

toolintheJavasphereisAnt.Ant(seeChapter1)isafinetool

andahugelysuccessfulopensourceproject.MillionsofJava

developersarefamiliarwithit.And,aswewillseethroughout

therestofthebook,thereishardlyaJavatoolinexistencethat

doesn'tintegratewithAnt.

However,whenyouwritealotofAntbuildscripts,youfind

yourselfaskingyourself(andotherteamgmembers)thesame

questionsoverandoveragain:Wherewillthesourcecodego?

Whatabouttheunittests?Howdowehandledependencies?

Howwillwebundleupthedeliverableapplication?Whatshall

wecallthemaintargets?Individually,Antletsyoudealwith

eachofthesetaskswithahighdegreeofflexibilityandpower.

However,youstillhavetowritethetasksfromscratchor

duplicateandmodifyanAntscriptfromapreviousproject.And

whenyoumovetoanewprojectorcompany,youneedtoask

thesequestionsonceagainto(beginto)understandthebuild

processinplace.

Many(althoughnotall)projectsdofollowfairlycommonand

well-knownpatterns.Alotofwhatyouneedtoconfigurein

yourbuildprocessisprettymuchrun-of-the-mill.Italways

seemsashametoredotheworkagainforeachnewproject.

Mavencanhelpyouhere.Maventakesalotofthegruntwork

outofthebuildprocess,andtriestoleverthecombined

experienceandbestpracticeofalargecommunityof

developers.Byadheringtoacertainnumberofconventionsand

bestpractices,Mavenletsyouremovethedrudgeryofallthe

low-leveltasksinyourbuildscripts.Intherestofthischapter,

wewillseehow.



2.3.InstallingMaven

Inthischapter,wewillgothroughhowtoinstallMaven2on

variousplatforms.Thebasicinstallationprocessis

straightforward,andisthesameforallplatforms.Mavenisa

pureJavatool,sofirstofallyouneedtoensurethatthereisa

recentversionofJava(1.4orlater)onyourmachine.Then,

downloadthelatestdistributionfromtheMavendownload

site[*]andextractitintoanappropriatedirectory.Finally,just

addthebinsubdirectorytothesystempath.

[*]http://maven.apache.org/download.html



IfyouarefamiliarwithinstallingJavatools,thisshouldbe

enoughtogetyoustarted.Intherestofthischapter,we

discusssomemoredetailedenvironment-specific

considerations.



2.3.1.InstallingMavenonaUnixMachine

Inthischapter,werunthroughhowtoinstallMavenintoaUnix

environment.

InstallingMaveninaUnix-basedenvironmentisarelatively

simpletask.Downloadthelatestversionintheformatofyour

choice,andextractittoanappropriatedirectory.Conventions

varygreatlyfromonesystemtoanother,andfromonesystem

administratortoanother:Igenerallyplacethemaven

installationinanonuser-specificdirectorysuchas/usr/local,as

shownhere:

#cd/usr/local

#tarxvfzmaven-2.0.7-bin.tar.gz

#ls

Thiswillextractthemaveninstallationinadirectorycalled

maven-2.0.7.Forconvenience,onaUnixsystem,Igenerally

createasymboliclinktothisdirectorytomakeupgradeseasier

tomanage:



#ln-smaven-2.0.7maven

#ls-al

total16

drwxr-xr-x3rootroot40962006-08-0613:18.

drwxr-xr-x53rootroot40962006-07-2021:32..

lrwxrwxrwx1rootroot112006-08-0613:17maven->maven-2.

drwxr-xr-x6rootroot40962006-08-0613:17maven-2.0.7

Nowjustaddthemaven/bindirectorytoyourenvironment

path.Typically,youwillsetthisupinoneofyourenvironment

initializationscripts(forexample,ifyouareusingBash,you

couldplacethisconfigurationinthe~/.bashrcfileifyoujust

needtosetitupforyouraccount,orin/etc/bashrcifyouwant

tosetitupforallusersonthismachine).Don'tforgettomake

surethattheJAVA_HOMEenvironmentvariableisdefinedas

well.Hereisatypicalexample:

PATH=$PATH:/usr/local/maven/bin

JAVA_HOME=/usr/lib/jvm/java

exportPATHJAVA_HOME

Nowcheckthatitworksbyrunningthemavencommandfrom

thecommandline:

#mvn--version

Mavenversion:2.0.7



2.3.2.InstallingMavenonaWindowsMachine

InstallingMavenonaWindowsmachineisalsorelatively

straightforward,althoughtheapplicationstilllacksthegraphical

installationpackagefamiliartoWindowsusers.First,download

andunziptheMavendistributionintoanappropriatedirectory.

MostWindowsmachineswillhaveagraphicalcompression

utilitythatyoucanusetoextracttheZIPfile,althoughifyou

arestuck,youcanalwaysusetheJavajarcommand-linetool,

asshownhere:



C:>jar-xfmaven-2.0.4-bin.zip

InFigure2-1,Mavenhasbeeninstalledinthe

P:\tools\maven\maven-2.0.4directory,althoughofcourse

youcaninstallitanywherethatsuitsyourparticularneeds.A

moreconventionalchoicemightbesomethinglikeC:\Program

Files\ApacheSoftwareFoundation\maven-2.0.4.Becauseit

isaJavaapplication,MavenalsoexpectstheJAVA_HOME

environmentvariabletobecorrectlydefined.

NextaddtheMavenbindirectorytoyourPATHuservariable

(Figure2-1).Youwillneedtoopenanewconsolewindowto

seethenewpathtakenintoaccount.

Figure2-1.AddingtheMavenbindirectorytothePATH

environmentvariable



Now,checkthatMaveniscorrectlyinstalledbyrunningmvn-version:

C:\>mvn--version

Mavenversion:2.0.4

NowyoushouldhaveaworkingMavenenvironmentreadyto

go!



2.4.DeclarativeBuildsandtheMaven

ProjectObjectModel

2.4.1.AnIntroductiontoDeclarativeBuild

Management

Beforewelookathowtocreateandworkwithprojectsin

Maven,weneedtodiscusssomeofthebasics.Themost

fundamentaloftheseistheMavenProjectObjectModel,or

POM,whichwewilllookatinthischapter.Intheprocess,we

alsowillcoversomeimportantbasicprinciplesofMaven

development,aswellasalotofthekeyfeaturesofMaven.As

many,ifnotmost,newMavenusersarealreadyfamiliarwith

Ant,wewilllookathowtheMavenapproachdiffersfromthe

oneusedbyAnt,andhowthiscanhelpsimplifyyourbuilds.

ForAntusers,theMavenphilosophycantakealittlegettinguse

to.UnlikeAnt,whichisverymuchtask-oriented,Mavenusesa

highlydeclarativeapproachtoprojectbuilds.InAnt,for

example,youlistthetasksthatmustbeperformedtocompile,

test,anddeliveryourproduct.InMaven,bycontrast,you

describeyourprojectandyourbuildprocess,relyingon

conventionsandsensibledefaultvaluestodomuchofthegrunt

work.TheheartofaMaven2project,thePOM,describesyour

project,itsstructure,anditsdependencies.Itcontainsa

detaileddescriptionofyourproject,includinginformationabout

versioningandconfigurationmanagement,dependencies,

applicationandtestingresources,teammembersandstructure,

andmuchmore.ThePOMtakestheformofanXMLfile(called

pom.xmlbydefault),whichisplacedinyourprojecthome

directory.

Let'slookatapracticalexample.Oneofthemostfundamental

partsofanyJavabuildprocessinvolvescompilingyourJava

classes.InatypicalAntbuild,youwouldusethetask

(seeSection1.4)tocompileyourclasses.Thisinvolvesdefining

thedirectoryordirectoriescontainingyourJavasourcecode,

thedirectoryintowhichthecompiledclasseswillbeplaced,and



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

Chapter 2. Setting Up a Project Using Maven 2

Tải bản đầy đủ ngay(0 tr)

×