Sei sulla pagina 1di 10

:MAVEN:

Maven(accumulator of knowledge):standard way to build the projects, a clear


definition of what the project consisted of, an easy way to publish project
information and a way to share JARs across several projects.
Defination:"Maven is a declarative project management tool that decreases your
overall time
to market by effectively leveraging your synergies. It simultaneously reduces your
headcount and leads to
remarkable operational efficiencies.�
An individual Maven project's structure and contents are declared in a Project
Object Model (POM), which forms the basis of the entire Maven system. The key value
to developers from Maven is that it takes a declarative approach rather than
developers creating the build process themselves, referred to as "building the
build". Maven allows developers to declare goals and dependencies and rely on
Maven�s default structures and plugin capabilities to build the project. Much of
the project management and build orchestration (compile, test, assemble, install)
is effectively delegated to the POM and the appropriate plugins. Developers can
build any given project without having to
understand how the individual plugins work (scripts in the Ant world).
Given the highly inter-dependent nature of projects in open source, Maven�s ability
to standardize locations for source files, documentation, and output, to provide a
common layout for project documentation, and to retrieve project dependencies from
a shared storage area makes the building process much less time consuming, and much
more transparent
Maven's primary goal is to allow a developer to comprehend the complete state of a
development effort in the shortest period of time. In order to attain this goal
there are several areas of concern that Maven attempts to deal with:
Making the build process easy
Providing a uniform build system
Providing quality project information
Providing guidelines for best practices development
Allowing transparent migration to new features
Maven allows a project to build using its project object model (POM) and a set of
plugins that are shared by all projects using Maven, providing a uniform build
system.
Maven provides plenty of useful project information that is in part taken from your
POM and in part generated from your project's sources. For example, Maven can
provide:
Change log document created directly from source control
Cross referenced sources
Mailing lists
Dependency list
Unit test reports including coverage
Organizations and projects that adopt Maven benefit from:
� Coherence - Maven allows organizations to standardize on a set of best practices.
Because Maven projects adhere to a standard model they are less opaque. The
definition of this term from the American Heritage dictionarycaptures the meaning
perfectly: �Marked by an orderly, logical, and aesthetically consistent relation of
parts.�
� Reusability - Maven is built upon a foundation of reuse. When you adopt Maven you
are effectively reusing the best practices of an entire industry.
� Agility - Maven lowers the barrier to reuse not only of build logic but of
components. When using Maven it is easier to create a component and integrate it
into a multi-project build. It is easier for developers to jump between different
projects without a steep learning curve that accompanies a custom, home-grown build
system.
� Maintainability - Organizations that adopt Maven can stop building the build, and
start focusing on the application. Maven projects are more maintainable because
they have fewer surprises and follow a common model.

There are three primary conventions that Maven employs to promote a familiar
development
environment:
� Standard directory layout for projects:
The first convention used by Maven is a standard directory layout for project
sources, project resources, configuration files, generated output, and
documentation. These components are generally referred to as project content. Maven
encourages a common arrangement of project content so that once you are familiar
with the standard locations, you will be able to navigate within any Maven project
you encounter in the future.
You can override any of Maven's defaults to create a directory layout of your
choosing, but, when you do this, you need to ask yourself if the extra
configuration that comes with customization is really worth it. If you have no
choice in the matter due to organizational policy or integration issues with
existing systems you might be forced to use a directory structure that diverges
from Maven's defaults.
In this case, you will be able to adapt your project to your customized layout at a
cost, increased complexity of your project's POM. So Follow the standard directory
layout, and you will make it easier to communicate about your project.
� The concept of a single Maven project producing a single output:
The second convention used by Maven is the concept of a Maven project producing one
primary output. To illustrate this point consider a set of sources for a
client/server-based application that contained the client code, the server code,
and some shared utility code. You could produce a single JAR file which contained
all the compiled classes, but Maven would encourage you to have three separate
projects: a project for the client portion of the application, a project for the
server portion of the application, and a project for the shared utility code. In
this scenario the code contained in each separate project has a different role to
play, or concern, and they should be separated.
The separation of concerns (SoC) principle states that a given problem involves
different kinds of concerns, which should be identified and separated to cope with
complexity and to achieve the required engineering quality factors such as
adaptability, maintainability, extendibility and reusability. If you have placed
all the sources together in a single project. the boundaries between our three
separate concerns can easily become blurred and a simple desire to reuse the
utility code could prove to be difficult. Having the utility code in a separate
project, in a separate JAR file, is much easier to reuse. Maven pushes you to think
clearly about the separation of concerns when setting up your projects because
modularity leads to reuse.
� Standard naming conventions:
The third convention, a set of conventions really, is a standard naming convention
for directories and a
standard naming convention for the primary output of a project. The conventions
provide clarity and
immediate comprehension. This is important if there are multiple projects involved,
because the
naming convention keeps them separate in a logical, easy to see manner.

*Maven local repository:


The maven local repository is a local folder that is used to store all your
project�s dependencies (plugin jars and other files which are downloaded by Maven).
In simple, when you build a Maven project, all dependency files will be stored in
your Maven local repository.
By default, Maven local repository is default to .m2 folder :
Windows � C:\Documents and Settings\{your-username}\.m2
-Update Maven Local Repository:
Normally, I will change the default local repository folder from default .m2 to
another more meaningful name, for example, maven-repo.
Find {M2_HOME}\conf\setting.xml, update localRepository to something else.
{M2_HOME}\conf\setting.xml
<settings>
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<localRepository>D:/maven_repo</localRepository>

*Maven central repository:


When you build a Maven�s project, Maven will check your pom.xml file, to identify
which dependency to download. First, Maven will get the dependency from your local
repository Maven local repository, if not found, then get it from the default Maven
central repository � http://repo1.maven.org/maven2/
The maven center repository website is revamped, directory browsing is no longer
available. Instead, you will be redirected to http://search.maven.org/. It�s much
better, now you have a search function.
NOTE:The directory browsing feature is disabled, But, when you build the Maven
project, it will still get the dependency from �http://repo1.maven.org/maven/� ,
you can verify from the Maven output.

*Maven remote repository:


According to Apache Maven :
Downloading in Maven is triggered by a project declaring a dependency that is not
present in the local repository (or for a SNAPSHOT, when the remote repository
contains one that is newer). By default, Maven will download from the central
repository.
In Maven, when you�re declared library does not exist either inlocal repository nor
Maven center repository, the process will stop and output error messages to your
Maven console.
#Example:
The org.jvnet.localizer is only available at Java.net repository.
pom.xml:
<dependency>
<groupId>org.jvnet.localizer</groupId>
<artifactId>localizer</artifactId>
<version>1.8</version>
</dependency>
When you build this Maven project, it will fail and output dependency not found
error message.

To tell Maven to get the dependency from Java.net, you need to declared a remote
repository in your pom.xml file like this :
pom.xml:
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/public/</url>
</repository>
</repositories>

-->Now, Maven�s dependency library look-up sequences is changed to :


Search in Maven local repository, if not found, go step 2, else exit.
Search in Maven central repository, if not found, go step 3, else exit.
Search in java.net Maven remote repository, if not found, prompt error message,
else exit.

*Include custom library into maven local repository:


Here are 2 cases that you need to issue Maven�s command to include a jar into the
Maven local repository manually.
-The jar you want to use doesn�t exist in the Maven center repository.
-You created a custom jar, and need to use for another Maven project.
There are still many jars that doesn�t support Maven.
Example:
kaptcha, a popular third party Java library, which is used to generate �captcha�
image to stop spam, but it�s not available in the Maven center repository.
1. mvn install
Download the �kaptcha�, extract it and copy the kaptcha-version.jar to somewhere
else, for example, c drive. Issue following command :
mvn install:install-file -Dfile=c:\kaptcha-{version}.jar
-DgroupId=com.google.code -DartifactId=kaptcha -Dversion={version} -Dpackaging=jar
DEMO:
D:\>mvn install:install-file -Dfile=c:\kaptcha-2.3.jar
-DgroupId=com.google.code
-DartifactId=kaptcha -Dversion=2.3 -Dpackaging=jar
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO]
------------------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [install:install-file] (aggregator-style)
[INFO]
------------------------------------------------------------------------
[INFO] [install:install-file]
[INFO] Installing c:\kaptcha-2.3.jar to
D:\maven_repo\com\google\code\kaptcha\2.3\kaptcha-2.3.jar
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO]
------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Tue May 12 13:41:42 SGT 2009
[INFO] Final Memory: 3M/6Ms
[INFO]
------------------------------------------------------------------------
Now, the �kaptcha� jar is copied to your Maven local repository.
2. pom.xml
After installed, just declares the kaptcha coordinate in pom.xml.
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3</version>
</dependency>
3. Done
Build it, now the �kaptcha� jar is able to retrieve from your Maven local
repository.

Discussions:
??How do I find out which settings.xml file maven is using?
A1:Use the Maven debug option, ie mvn -X
A1:The settings file is never created automatically, you must create it yourself,
whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml e.g.
C:\Users\YourUserName\.m2\settings.xml on Windows or
/home/YourUserName/.m2/settings.xml on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

//TODO Understanding each element in settngs.xml

*Creating Maven projects from the command line:


-What is Archetype?:
Archetype is a Maven project templating toolkit. An archetype is defined as an
original pattern or model from which all other things of the same kind are made.
The names fits as we are trying to provide a system that provides a consistent
means of generating Maven projects. Archetype will help authors create Maven
project templates for users, and provides users with the means to generate
parameterized versions of those project templates.
Using archetypes provides a great way to enable developers quickly in a way
consistent with best practices employed by your project or organization. Within the
Maven project we use archetypes to try and get our users up and running as quickly
as possible by providing a sample project that demonstrates many of the features of
Maven while introducing new users to the best practices employed by Maven.

If we use the archetype:generate goal, Maven will step you through the options
using a command-line wizard.
mvn archetype:generate
The Following appears in the command prompt:

C:\Users\john\projects>mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO]
------------------------------------------------------------------------
[INFO] Building Pet Database Core Module
[INFO] task-segment: [archetype:generate] (aggregator-style)
[INFO]
------------------------------------------------------------------------
[INFO] Preparing archetype:generate
[INFO] No goals needed for project - skipping
[INFO] Setting property: classpath.resource.loader.class =>
'org.codehaus.plexus.velocity.ContextCla
ssLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO] [archetype:generate]
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart
(org.apache.maven.archetypes:maven-arc
hetype-quickstart:1.0)
Choose archetype:
1: internal -> appfuse-basic-jsf (AppFuse archetype for creating a web
application with Hibernate, S
pring and JSF)
2: internal -> appfuse-basic-spring (AppFuse archetype for creating a
web application with Hibernate
, Spring and Spring MVC)
3: internal -> appfuse-basic-struts (AppFuse archetype for creating a
web application with Hibernate
, Spring and Struts 2)
4: internal -> appfuse-basic-tapestry (AppFuse archetype for creating a
web application with Hiberna
te, Spring and Tapestry 4)
5: internal -> appfuse-core (AppFuse archetype for creating a jar
application with Hibernate and Spr
ing and XFire)
6: internal -> appfuse-modular-jsf (AppFuse archetype for creating a
modular application with Hibern
ate, Spring and JSF)
7: internal -> appfuse-modular-spring (AppFuse archetype for creating a
modular application with Hib
ernate, Spring and Spring MVC)
8: internal -> appfuse-modular-struts (AppFuse archetype for creating a
modular application with Hib
ernate, Spring and Struts 2)
9: internal -> appfuse-modular-tapestry (AppFuse archetype for creating
a modular application with H
ibernate, Spring and Tapestry 4)
10: internal -> maven-archetype-j2ee-simple (A simple J2EE Java
application)
11: internal -> maven-archetype-marmalade-mojo (A Maven plugin
development project using marmalade)
12: internal -> maven-archetype-mojo (A Maven Java plugin development
project)
13: internal -> maven-archetype-portlet (A simple portlet application)
14: internal -> maven-archetype-profiles ()
15: internal -> maven-archetype-quickstart ()
16: internal -> maven-archetype-site-simple (A simple site generation
project)
17: internal -> maven-archetype-site (A more complex site project)
18: internal -> maven-archetype-webapp (A simple Java web application)
19: internal -> struts2-archetype-starter (A starter Struts 2
application with Sitemesh, DWR, and Sp
ring)
20: internal -> struts2-archetype-blank (A minimal Struts 2
application)
21: internal -> struts2-archetype-portlet (A minimal Struts 2
application that can be deployed as a
portlet)
22: internal -> struts2-archetype-dbportlet (A starter Struts 2 portlet
that demonstrates a simple C
RUD interface with db backing)
23: internal -> struts2-archetype-plugin (A Struts 2 plugin)
24: internal -> shale-archetype-blank (A blank Shale web application
with JSF)
25: internal -> maven-adf-archetype (Archetype to ease the burden of
creating a new application base
d with ADF)
26: internal -> data-app (A new Databinder application with sources and
resources.)
27: internal -> jini-service-archetype (Archetype for Jini service
project creation)
28: internal -> softeu-archetype-seam (JSF+Facelets+Seam Archetype)
29: internal -> softeu-archetype-seam-simple (JSF+Facelets+Seam (no
persistence) Archetype)
30: internal -> softeu-archetype-jsf (JSF+Facelets Archetype)
31: internal -> jpa-maven-archetype (JPA application)
32: internal -> spring-osgi-bundle-archetype (Spring-OSGi archetype)
33: internal -> confluence-plugin-archetype (Atlassian Confluence
plugin archetype)
34: internal -> jira-plugin-archetype (Atlassian JIRA plugin archetype)
35: internal -> maven-archetype-har (Hibernate Archive)
36: internal -> maven-archetype-sar (JBoss Service Archive)
37: internal -> wicket-archetype-quickstart (A simple Apache Wicket
project)
38: internal -> quickstart (A simple Apache Tapestry 5 Project)
39: internal -> scala-archetype-simple (A simple scala project)
40: internal -> lift-archetype-blank (A blank/empty liftweb project)
41: internal -> lift-archetype-basic (The basic (liftweb) project)
42: internal -> cocoon-22-archetype-block-plain
([http://cocoon.apache.org/2.2/maven-plugins/])
43: internal -> cocoon-22-archetype-block
([http://cocoon.apache.org/2.2/maven-plugins/])
44: internal -> cocoon-22-archetype-webapp
([http://cocoon.apache.org/2.2/maven-plugins/])
Choose a number:
(1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/
31/32/33/34/35/36/37/38/39/40/41/42/43/44) 15: :18

The default archetype is the "maven-archetype-quickstart", the simple Maven project


structure that we are all familiar with. But there are plenty of others to choose
from, including all of the appfuse archetypes, and many other technology stacks.

Next, you are prompted for the groupId, artifactId, version and package:

[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp:


checking for updates from maven-
archetype-webapp-repo
[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp:
checking for updates from centra
l
Downloading:
http://localhost:8081/nexus/content/groups/public/org/apache/maven/arche...
downloaded
Define value for groupId: : com.wakaleo.onlinebank
Define value for artifactId: : onlinebank-core
Define value for version: 1.0-SNAPSHOT: :
Define value for package: : com.wakaleo.onlinebank.core

We can review our choices, and, go ahead and create the project:
Confirm properties configuration:
groupId: com.wakaleo.onlinebank
artifactId: onlinebank-core
version: 1.0-SNAPSHOT
package: com.wakaleo.onlinebank.core
Y: :
Y: :
[INFO]
----------------------------------------------------------------------------
[INFO] Using following parameters for creating OldArchetype: maven-
archetype-quickstart:RELEASE
[INFO]
----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.wakaleo.onlinebank
[INFO] Parameter: packageName, Value: com.wakaleo.onlinebank.core
[INFO] Parameter: package, Value: com.wakaleo.onlinebank.core
[INFO] Parameter: artifactId, Value: onlinebank-core
[INFO] Parameter: basedir, Value: C:\Users\john\projects\onlinkbank
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from
generated POM *******************
****
[INFO] OldArchetype created in dir:
C:\Users\john\projects\onlinkbank\onlinebank-core
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO]
------------------------------------------------------------------------
[INFO] Total time: 27 seconds
[INFO] Finished at: Thu Aug 07 19:51:37 NZST 2008
[INFO] Final Memory: 8M/15M
[INFO]
------------------------------------------------------------------------

Another command with the group Id and artifact Id in the command prompt
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes
-DgroupId=com.mycompany.app -DartifactId=my-app

Once you have executed this command, you will notice a few things have happened.
First, you will notice that a directory named my-app has been created for the new
project, and this directory contains a file named pom.xml that should look like
this:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

pom.xml contains the Project Object Model (POM) for this project. The POM is the
basic unit of work in Maven. This is important to remember because Maven is
inherently project-centric in that everything revolves around the notion of a
project. In short, the POM contains every important piece of information about your
project and is essentially one-stop-shopping for finding anything related to your
project.

For pom.xml refer maven.html:)

A Build Lifecycle is Made Up of Phases

Each of these build lifecycles is defined by a different list of build phases,


wherein a build phase represents a stage in the lifecycle.

For example, the default lifecycle has the following build phases (for a complete
list of the build phases, refer to the Lifecycle Reference):

validate - validate the project is correct and all necessary information is


available
compile - compile the source code of the project
test - test the compiled source code using a suitable unit testing framework.
These tests should not require the code be packaged or deployed
package - take the compiled code and package it in its distributable format,
such as a JAR.
integration-test - process and deploy the package if necessary into an
environment where integration tests can be run
verify - run any checks to verify the package is valid and meets quality
criteria
install - install the package into the local repository, for use as a
dependency in other projects locally
deploy - done in an integration or release environment, copies the final
package to the remote repository for sharing with other developers and projects.

These build phases (plus the other build phases not shown here) are executed
sequentially to complete the default lifecycle. Given the build phases above, this
means that when the default lifecycle is used, Maven will first validate the
project, then will try to compile the sources, run those against the tests, package
the binaries (e.g. jar), run integration tests against that package, verify the
package, install the verifed package to the local repository, then deploy the
installed package in a specified environment.

To do all those, you only need to call the last build phase to be executed, in this
case, deploy:
mvn deploy
That is because if you call a build phase, it will execute not only that build
phase, but also every build phase prior to the called build phase. Thus, doing
mvn integration-test
will do every build phase before it (validate, compile, package, etc.), before
executing integration-test.
There are more commands that are part of the lifecycle, which will be discussed in
the following sections.
It should also be noted that the same command can be used in a multi-module
scenario (i.e. a project with one or more subprojects). For example:
mvn clean install
This command will traverse into all of the subprojects and run clean, then install
(including all of the prior steps).
-A Build Phase is Made Up of Goals:
However, even though a build phase is responsible for a specific step in the build
lifecycle, the manner in which it carries out those responsibilities may vary. And
this is done by declaring the goals bound to those build phases.
A goal represents a specific task (finer than a build phase) which contributes to
the building and managing of a project. It may be bound to zero or more build
phases. A goal not bound to any build phase could be executed outside of the build
lifecycle by direct invocation. The order of execution depends on the order in
which the goal(s) and the build phase(s) are invoked. For example, consider the
command below. The clean and package arguments are build phases while the
dependency:copy-dependencies is a goal.
mvn clean dependency:copy-dependencies package
If this were to be executed, the clean phase will be executed first (meaning it
will run all preceeding phases of the clean lifecycle, plus the clean phase
itself), and then the dependency:copy-dependencies goal, before finally executing
the package phase (and all its preceeding build phases of the default lifecycle).
Moreover, if a goal is bound to one or more build phases, that goal will be called
in all those phases.
Furthermore, a build phase can also have zero or more goals bound to it. If a build
phase has no goals bound to it, that build phase will not execute. But if it has
one or more goals bound to it, it will execute all those goals

Potrebbero piacerti anche