高活化高效铝合金阳极:maven

来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 22:17:58

Maven 2.0: Compile, Test, Run, Deploy, and More

by Chris Hardin
03/29/2006

The hardest part of getting started with a Java application is, well,getting started. So many logistical decisions have to be made up front.Where should the Java source files go? Where do I place unit testing?Where will we store dependency .jars? How will the project be built,documented, tested, and deployed? The choices made at this stage willfollow a developer for the rest of the project. It's up to you whetherthose choices will haunt you or prove you to be a master Java architectlater on. We'll assume the latter is the goal we are striving for, andnow we just need a starting point.

There are many tools out there for building a Java project, including Ant. Ant has been on the top of many a developer's list as the revolutionary tool that got them out of the world of make. For those of you not familiar with make,it'll be enough t say that it just isn't the best tool to use forbuilding Java projects, since it isn't platform-independent and it isn'tthat easy to use. Ant came along and changed all that by providing aplatform-independent tool that uses an XML configuration file, theinfamous build.xml. Ant has enjoyed heavy popularity with its many advantages, but it also has some drawbacks. The build.xmlfiles can be extremely terse, and their use requires the developer tolearn the syntax up front. While the learning curve isn't too steep, aJava developer's time could be better spent doing, well, development.

Maven is thenew kid on the block, much like Ant was just a few short years ago.Maven 1.0 has been around for a few years and it was accepted by a wideaudience of developers as an Ant replacement, but it offered very littlerelief from the old Ant build.xml file. Maven 1.0 was slow andclunky and using it was almost as difficult as getting started on aproject with Ant. In fact, it was Ant at its core, and after an almostcomplete rewrite, Maven 2.0 was born.

The Benefits of Maven 2.0

The benefits of Maven 2.0 are numerous, as it does more than merelybuild your projects. If you are just starting a new Java project and youneed to get started fast, Maven 2.0 will have you up an running inminutes. The following are some of the advantages of Maven 2.0:

  • Standardized project layout and project structure generator.
  • Standardized dependency-management mechanism.
  • Multiple project support.
  • Instant downloads of new plugins and features as the developer needs them.
  • Website generation for up-to-date project information.
  • Integration with source control: CVS and Subversion.

The list above is just a short list of the features available inMaven 2.0. These alone make Maven 2.0 a solid choice for a buildmanagement system. Now that we know what Maven is, let's look at how toget started.

Getting Started

The first thing we want to do is set up our directory structure.Wait--there is no need to do it by hand. Maven can do it for you,depending on the type of project that you are developing. Once you havedownloaded and extracted the latest distribution of Maven 2.0, you should add the bin directory of the Maven distribution to your system path. You can run mvn -version to test your installation.

Now that we have the tool installed, let's look at the example of creating a simple Java project. Maven uses archetypesto determine how the directory structure will be laid out. There areseveral built-in archetypes or you can write one of your own.

mvn archetype:create -DgroupId=com.oreilly -DartifactId=my-app

Voila! We now have our project layout.

my-app----src----main-   ----java-       ----com-           ----oreilly----test----java----com----oreilly

Yes, it's that easy. It should be noted that this directory structurecan be overridden by creating a new archetype, but deviating from thestructure is not recommended, since one of the benefits of Maven is thestandard directory structure. The directory structure contains twosource trees: one for your Java application source code and one for yourunit test code. You may also have noticed that the first time you ranMaven, it did some downloading. Maven will update itself with theappropriate functionality based on what plugin you use when you invokethe tool. Maven, by default, will get its updates from the Ibiblio repository. You can override Maven's choice of a remote repository in the conf directory of the Maven distribution or in the project itself.

You should also have noticed that Maven created a pom.xml file in the my-app directory. This is the meat and potatoes of your project. The pom.xmlfile is a set of instructions for Maven that tells it how to build theproject and includes other special instructions. (POM is an acronym for"project object model.") By default, Maven also includes the JUnitdependency to encourage unit testing.

4.0.0com.oreillymy-appjar1.0-SNAPSHOTMaven Quick Start Archetypehttp://maven.apache.orgjunitjunit3.8.1test

Now that we have our project created, we can add in our code andutilize a whole new bag of Maven tricks. Note that the followingcommands must run in the same directory as the pom.xml file.



  • mvn test: Runs the JUnit tests for the application.
  • mvn package: Creates a .jar file from our project.
  • mvn install: Adds our project .jar to the repository for use as a dependency if needed.
  • mvn site: Generates the project website.
  • mvn clean: Cleans the output created in the target directory.
  • mvn eclipse:eclipse: Generates the Eclipse project file.

Let's look at something a little more complex. Starting a Java webproject by hand can be even more time-consuming than starting a simpleJava project by hand, but Maven makes it just as easy. The example below(ordinarily a single line, but wrapped to suit the web page format)sets up the project structure.

mvn archetype:create -DgroupId=com.oreilly-DartifactId=Oreilly-DarchetypeArtifactId=maven-archetype-webapp

The resulting structure looks like this:

Oreilly----src----main----resources----webapp----WEB-INF

This time, our project was set up a little differently to support web resources that we will include in the .war file. The pom.xml file will contain a line that indicates that the project should be packaged into a .war file: war. Now we are ready to create the .war file with mvn package. Don't worry about how you'll get your dependencies into the WEB-INF/lib directory; Maven will include them automatically if the dependency's scope is set to compile. We can also change the name of the .war file by simply adding the following to our pom.xml:

PromoteC

Dependency Management

Now that we have created our project structure, written some code,and tested and compiled our application, we can move on look at howMaven handles dependencies. In order to add a dependency to yourproject, you need to add it to your pom.xml; the next time you run Maven, it will get that dependency from the Ibiblio repository and add it to your build path.

There are some very important things to remember about dependencies.The biggest inconvenience currently with Maven is that Sun .jars are notavailable through a Maven repository at the time of this writing. Thisis due to the licensing restrictions that Sun places on its code. Towork around this issue, you have to download and install the code intoyour local repository or make a external declaration for a dependencylocation at a point on your file system. Hopefully, Sun will createtheir own Maven repository soon, but Maven will have to be updated toprompt the user to accept the licensing agreement before Maven candownload the resource.

Another inconvenience is that sometimes you might be using a librarythat is very recent and might not exist in a remote repository. Anotherpossibility is that you just might be developing with no internet accessand just want to have all of your dependencies available locally. Thebest solution for these issues is to install the .jar in your localrepository. It is also convenient to store your local repository on aweb server, so that your entire development team can benefit andeveryone doesn't have to manage his or her own repository. Changing theMaven repository path is as simple as editing the settings.xml file in the conf directory of the Maven distribution.

Using dependencies in Maven is simple. Let's look at adding a dependency to our pom.xml file above. We already have JUnit, but let's add the powerful Quartzlibrary to our project. Quartz is an open source scheduling mechanismwritten entirely in Java and is a great choice for all of yourscheduling needs.

quartzquartz1.5.1compile

That is all we need to add to the element in order to get Maven to download and use Quartz as a dependencyfor our project. Don't worry about Quartz having dependencies. A Mavenrepository will contain information about dependencies for dependenciesand when Maven downloads Quartz, all of its dependencies will also bedownloaded. In order to verify that the 1.5.1 version of Quartz existsin Ibiblio, we can browse the Maven repository. Note the use of the scope parameter; this tells Maven at which stage the dependency is needed. In the case of JUnit, we used the scope testto tell Maven that this dependency is only needed in the testing phaseand not as a runtime resource. Here is a guide to the available scopes.

  • compile: This is the default. States that the resource must be present for all tasks.
  • test: Runs all test cases.
  • runtime: This indicates that the resource is only needed as a runtime resource.
  • provided: This is for items that you expect to already be provided as part of the JDK or application server classpath.

Now, what about those pesky Sun .jars or the .jars that we need thatwe can't find in a remote repository? We have to install those .jarsinto our local repository manually with Maven. Don't worry--this isnowhere near as hard as it sounds. For the sake of example, we'llinstall the Java Activation Framework .jar. First we have to download itfrom Sun, and then we can use Maven to import it into our localrepository. It is also possible to install a missing .jar into Ibiblioyourself using some instructions in the Maven guide to uploading artifacts to Ibiblio.



mvn install:install-file -Dfile=activation.jar-DgroupId=javax.activation -DartifactId=activation-Dversion=1.0 -Dpackaging=jar

Now the .jar is installed in our local repository just like any otherdependency for our project. We only need to add the dependencydeclaration and we are all set. Remember to make sure your versioninformation is correct when adding .jars and when declaring them asdependencies. A mismatch will cause Maven to fail when it tries to findthe resource. If you need help with the standard naming parameters whenimporting Sun .jars, you can refer to Maven's list of standard Sun .jar names. Remember, you cannot publicly distribute these .jars through a repository at this time without violating Sun's terms of use.

javax.activationactivation1.0compile

You may be tempted to store dependencies in a source controlrepository; source control was never meant for this task. Dependenciesare transient and are generally versioned by a number scheme. That beingsaid, you definitely would want to make sure you back up your internalremote repository, if you have one, to make sure you don't lose all ofthe custom additions you've made, in case the repository server crashesand cannot be recovered. Not storing dependencies in source control willalso save vast amounts of disk space on the source-control repositoryserver.

Configuring Repositories

It would be inconvenient for every developer on a project to have to configure a repository in his or her conf directory, so Maven has the ability to look at multiple repositories at the same time and configure them all in the pom.xml file. Let's look at an example of how we could use multiple repositories with our application. In the following excerpt from pom.xml,we set up two repositories for Maven to be able to find dependencies.Ibiblio is always the default for Maven, but we have added Planet Mirroras a backup. We might also want to make the second repository our localweb server that our team is using as a repository.

IbiblioIbibliohttp://www.ibiblio.org/maven/PlanetMirrorPlanet Mirrorhttp://public.planetmirror.com/pub/maven/

Building Multiple Projects using a Parent pom.xml

It's fairly common for software companies to have multiple projectsthat are built into the main product. Maintaining the dependency chainand building the entire product at one time can be a challenge, but withMaven, it's simple. If you create a parent pom.xml that refersto other submodules, Maven will handle the complete build for you. Thedependency mechanism works by analyzing each submodule's pom.xmlfor dependencies and building the projects in the order in which theydepend on each other. The order that you place the submodules in theparent would not matter if each project called out its dependenciesexplicitly, but for the sake of other developers, it is best to makesure that the order in the parent pom.xml is the same order in which you want the subprojects to be built. Let's look at an example.

The master pom.xml is as follows:

4.0.0com.oreilly1.0-SNAPSHOTmy-apppomCommonUtilitiesApplicationWebApplication

We need to make sure that all three of the dependency .jars are included in the WebApplication submodule, so we need to declare them as dependencies. In this example, our Utilities project depends on the Common project, so we would need to add a dependency to the Utilities project for Common. The same goes for our Application submodule, because it would depend on Common and Utilities, and Utilities would depend on Common.If there were 60 submodules in this example that all depend on eachother, it would be difficult for a new developer to figure out whatprojects depend upon others, so this is precisely the reason we makesure that the order of the projects is clear in the parent pom.xml.

Here are the Utility module's dependencies

com.oreillyCommon1.0-SNAPSHOT

Here's how to state the Application module's dependencies

com.oreillyCommon1.0-SNAPSHOTcom.oreillyUtilities1.0-SNAPSHOT

Finally, the WebApplication module dependencies are as follows:

com.oreillyCommon1.0-SNAPSHOTcom.oreillyUtilities1.0-SNAPSHOTcom.oreillyApplication1.0-SNAPSHOT

Now we just need to add an element to each submodule's pom.xml file declaring that they are part of one logical build.

com.oreillymy-app1.0-SNAPSHOT

In the same directory as the master pom.xml file, we have our project directories: Common, Utilities, Application, and WebApplication. Now when we run mvn package in the directory with the master pom.xml file, each project will be built in turn as they depend upon one another.

Plugins and Reports

Maven 2.0 has a wide array of plugins that are available.Unfortunately, since Maven was rewritten, Maven 1.0 plugins won't workand cannot be used with Maven 2.0. However, there are several Maven 2.0plugins already available for use. The following plugin configurationfor pom.xml is an example straight from the Maven 2.0 website. This plugin is used to configure compiler options.



  org.apache.maven.pluginsmaven-compiler-plugin1.51.5

The Maven reporting plugins can be used to generate different reportsthat will be available when you generate the project website using mvn site. Here is an example of how to configure one of those plugins using the element.

 org.apache.maven.pluginsmaven-project-info-reports-plugin

The Maven Plugin Matrix is really useful for figuring out what Maven plugins are available for which version of Maven.

Maven and Eclipse

How could the world's greatest IDE get any better? With a Maven 2plugin that assists in searching for dependencies and adds them to pom.xmlautomatically. Maven has an Eclipse plugin that will enable Maven forany project, although it is best to create your project with Maven firstand then generate your Eclipse project file with mvn eclipse:eclipse, just so that you get the directory structure perfect the first time.

You can install the Eclipse plugin through the updater in Eclipse itself using http://m2eclipse.codehaus.org/as the site for the plugin. After installing and restarting the IDE,you need to configure the Maven plugin in Eclipse's preferences byfilling in the location of the local repository. This is an importantstep, because if the default repository for Eclipse doesn't match yourdefault, Maven will re-download your dependencies. After configuration,import the project into Eclipse, right-click on the project, and chooseMaven 2 -> Enable. Now you can go back through that step and you'llhave more options like Add Dependency, which will bring up a search boxso you can search for dependencies and add them; the plugin will edityour pom.xml file for you.

The plugin will build your project using Maven in much the same waythat Eclipse can handle building with Ant. If you would like moreinformation on Eclipse integration with Maven, check out the guide to using Eclipse with Maven 2.x on the Maven site.

On the other hand, if you are an IntelliJ fan, you can accomplish the same task by running mvn idea:idea.These IDE integrations can save ramp-up time for developers. Forexample, if a developer adds some new aspect to a project, otherdevelopers on the team can just re-check out the project files fromtheir source control repository and save the time of each developerhaving to make the IDE configuration.

Conclusion

Maven 2.0 has many useful features and performs extremely well. Themost laudable part of Maven is the use of standard directory structuresand deployments. This allows developers to move from project to projectand not have to learn anything new about the structure or go throughspecial instructions on how to build it. Practical applications forMaven also extend into custom build systems for large softwareengineering shops. Maven can be fully scripted and queued to run nightlyand deploy distributions as well as send out notifications to users.From the documentation side, it's extremely handy to have the projectwebsite tools built in so that when the project build is complete, youcan see a current status of all development.

There is no doubt that Maven 2.0 blows Ant out of the water when itcomes to scalable build configurations, ease of use, and projectmanagement. In the next few years, we'll see more adoption of Maven asthe standard in build technology until someone comes along and buildsthe proverbial "better mousetrap." You can download Maven from the Mavenproject website listed below.

Resources

  • Maven project website

Chris Hardinis a Senior Java Architect in Birmingham, Alabama.


Return to ONJava.com.


Comments on this article

Showing messages 1 through 6 of 6.

  • Could you kindly mention how to use maven to create a SLSB facaded ejb app
    2006-04-30 17:19:29  ameelin [View]

    I have an app that uses ejb with spring(applicationContext.xml buried in ejb-jar), hibernate et al and running on JBoss. Want to "mavenize" the exisiting project(well by starting afresh:)
    [Ok which imbecile would use ejbs nowadays? I use SLSB ejb for the "distributedness" of the application and cluster support from JBoss application server. Using tomcat alone is not an option as I get out-of-the-box clustering with JBoss...so much for sidenote]

    What archetype should I use with Maven? A quickie example would be great.
  • Maven Artifacts
    2006-04-25 07:55:44  fj_rodriguez@hotmail.com [View]

    I would suggest to use a maven search to find the artifacts instead of browsing the ftp.
    e.g:

    http://mvnrepository.com

    or

    http://maven.ozacc.com/
  • Eclipse integration
    2006-03-31 01:04:12  otto [View]

    It should be noted that the Maven2 plugin for Eclipse (where Eclipse is the host) is not ready for production yet. There's a couple of shortcomings and lacking features.

    However, you don't necessarily need this to work with Maven2 and Eclipse. The Eclipse plugin for Maven2 (where Maven2 is the host) generates Eclipse project files from your POM and works well.
    • Eclipse integration
      2006-04-05 00:33:28  Rutul [View]

      I also face the same problem. But now come across with the new plugin offerred by Codehaus. You can check that from http://mevenide.codehaus.org/mevenide-ui-eclipse/features.html
      • Eclipse integration
        2006-04-18 14:20:41  mojavelinux [View]

        Actually, the mevenide plugin only works for the Maven 1.x series and not for Maven 2.x. In order to get similar functionality for Maven 2.x, you need to use the plugin created by Merenge, as mentioned at the end of the article.

        The Maven 2.x plugin for eclipse is really interesting because it includes the Maven dependencies as a library set, so if the pom file updates (and eclipse refreshes the resource), the library is automatically updated. There is no need for any copying of jar files at all.

        The situation with eclipse is not pretty right now, though. The eclipse:eclipse goal didn't initially anticipate the arrival of the eclipse plugin, so it takes some tweaking if you want to use both.
    • Eclipse integration
      2006-03-31 06:58:46  chrislhardin [View]

      The plugin has some problems, but I've been using it for a couple of months now and I've had few problems. Most of the time it works as advertised. It does however require a little effort up front.