Maven by Example 3.1. Introduction

来源:互联网 发布:matlab计算矩阵行列式 编辑:程序博客网 时间:2024/05/02 04:59

In this chapter, we introduce a simple project created from scratch using the Maven Archetype plugin. This elementary(基本的;初级的;[化学] 元素的) application provides us with the opportunity to discuss some core Maven concepts while you follow along with the development of the project.

Before you can start using Maven for complex, multi-module builds, we have to start with the basics. If you’ve used Maven before, you’ll notice that it does a good job of taking care of the details. Your builds tend to “just work,” and you only really need to dive into the details of Maven when you want to customize the default behavior or write a custom plugin. However, when you do need to dive into the details, a thorough understanding of the core concepts is essential. This chapter aims to introduce you to the simplest possible Maven project and then presents some of the core concepts that make Maven a solid build platform. After reading it, you’ll have a fundamental understanding of the build lifecycle, Maven repositories,dependency management, and the Project Object Model (POM).

3.1.1. Downloading this Chapter’s Example

This chapter develops a very simple example which will be used to explore core concepts of Maven. If you follow the steps described in this chapter, you shouldn’t need to download the examples to recreate the code produced by the Maven. We will be using the Maven Archetype plugin to create this simple project and this chapter doesn’t modify the project in any way. If you would prefer to read this chapter with the final example source code, this chapter’s example project may be downloaded with the book’s example code at:

http://www.sonatype.com/books/mvnex-book/mvnex-examples.zip

Unzip this archive in any directory, and then go to the ch-simple/directory. There you will see a directory named simple/ that contains the source code for this chapter.

3.2. Creating a Simple Project

To start a new Maven project, use the Maven Archetype plugin from the command line. Run thearchetype:generate goal, select default archetype suggested by pressing "Enter". This will use the archetypeorg.apache.maven.archetypes:maven-archetype-quickstart. Press"Enter" again to confirm the latest version of the archetype and then"Enter" to confirm the supplied parameters.

想不到创建默认工程的竟然会是maven的一个插件 

Warning

At the time of publication, the default maven-archetype-quickstart was item #312 in a list of 860 available archetypes. As more and more projects release Maven archetypes, this list will change and the number for the default archetype may change. When you run archetype:generate as shown below, the defaultmaven-archetype-quickstart will be selected by default.

$ mvn archetype:generate -DgroupId=org.sonatype.mavenbook \-DartifactId=simple \-Dpackage=org.sonatype.mavenbook \-Dversion=1.0-SNAPSHOT[INFO][INFO] ------------------------------------------------------------------------[INFO] Building Maven Stub Project (No POM) 1[INFO] ------------------------------------------------------------------------[INFO][INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>[INFO][INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<[INFO][INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---[INFO] Generating project in Interactive mode[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)Choose archetype:...312: remote -> org.apache.maven.archetypes:maven-archetype-quickstart (An archetype which contains a sample Maven project.)Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 312:Choose org.apache.maven.archetypes:maven-archetype-quickstart version:1: 1.0-alpha-12: 1.0-alpha-23: 1.0-alpha-34: 1.0-alpha-45: 1.06: 1.1Choose a number: 6:[INFO] Using property: groupId = org.sonatype.mavenbook[INFO] Using property: artifactId = simple[INFO] Using property: version = 1.0-SNAPSHOT[INFO] Using property: package = org.sonatype.mavenbookConfirm properties configuration:groupId: org.sonatype.mavenbookartifactId: simpleversion: 1.0-SNAPSHOTpackage: org.sonatype.mavenbook Y: :[INFO] ----------------------------------------------------------------------------[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.1[INFO] ----------------------------------------------------------------------------[INFO] Parameter: groupId, Value: org.sonatype.mavenbook[INFO] Parameter: packageName, Value: org.sonatype.mavenbook[INFO] Parameter: package, Value: org.sonatype.mavenbook[INFO] Parameter: artifactId, Value: simple[INFO] Parameter: basedir, Value: /Volumes/mac-data/dev/github/sonatype[INFO] Parameter: version, Value: 1.0-SNAPSHOT[INFO] project created from Old (1.x) Archetype in dir: /Volumes/mac-data/dev/github/sonatype/simple[INFO] BUILD SUCCESS...

mvn is the Maven command. archetype:generate is called a Maven goal. An archetype is defined as “an original model or type after which other similar things are patterned; a prototype.” A number of archetypes are available in Maven for anything from a simple application to a complex web application, and thearchetype:generate offers a list of archetypes to choose from. In this chapter, we are going to use the most basic archetype to create a simple skeleton starter project. The plugin is the prefixarchetype, and the goal isgenerate.

Once we’ve generated a project, take a look at the directory structure Maven created under the simple directory:

simple/(1)simple/pom.xml(2)/src//src/main/(3)/main/java/src/test/(4)/test/java

This generated directory adheres to the Maven Standard DirectoryLayout. We’ll get into more details later in this chapter, but for now, let’s just try to understand these few basic directories:

(1)

The Maven Archetype plugin creates a directory simple/ that matches theartifactId. This is known as the project’s base directory.

(2)

Every Maven project has what is known as a Project Object Model(POM) in a file namedpom.xml. This file describes the project,configures plugins, and declares dependencies.

(3)

Our project’s source code and resources are placed under src/main. In the case of our simple Java project this will consist of a few Java classes and some properties file. In another project,this could be the document root of a web application or configuration files for an application server. In a Java project, Java classes are placed insrc/main/java and classpath resources are placed insrc/main/resources.

(4)

Our project’s test cases are located in src/test. Under this directory, Java classes such as JUnit or TestNG tests are placed insrc/test/java, and classpath resources for tests are located in src/test/resources.

The Maven Archetype plugin generated a single class org.sonatype.mavenbook.App, which is a 13-line Java class with a static main function that prints out a message:

package org.sonatype.mavenbook;/** * Hello world! * */public class App{    public static void main( String[] args )    {        System.out.println( "Hello World!" );    }}

The simplest Maven archetype generates the simplest possible program:a program which prints "Hello World!" to standard output.

3.3. Building a Simple Project

directory that contains the pom.xml:

$ cd simple$ mvn install[INFO] Scanning for projects...[INFO] ----------------------------------------------------------------------[INFO] Building simple[INFO]task-segment: [install][INFO] ----------------------------------------------------------------------[INFO] [resources:resources][INFO] Using default encoding to copy filtered resources.[INFO] [compiler:compile][INFO] Compiling 1 source file to /simple/target/classes[INFO] [resources:testResources][INFO] Using default encoding to copy filtered resources.[INFO] [compiler:testCompile][INFO] Compiling 1 source file to /simple/target/test-classes[INFO] [surefire:test][INFO] Surefire report directory: /simple/target/surefire-reports

T E S T S

Running org.sonatype.mavenbook.AppTestTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.105 secResults :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0[INFO] [jar:jar][INFO] Building jar: /simple/target/simple-1.0-SNAPSHOT.jar[INFO] [install:install][INFO] Installing /simple/target/simple-1.0-SNAPSHOT.jar to \~/.m2/repository/com/sonatype/maven/simple/simple/1.0-SNAPSHOT/ \simple-1.0-SNAPSHOT.jar

You’ve just created, compiled, tested, packaged, and installed the simplest possible Maven project. To prove to yourself that this program works, run it from the command line.

$ java -cp target/simple-1.0-SNAPSHOT.jar org.sonatype.mavenbook.AppHello World!
$ ls target/
classes/                 maven-status/            surefire-reports/
maven-archiver/          simple-1.0-SNAPSHOT.jar  test-classes/

3.4. Simple Project Object Model

Simple Project’s pom.xml file. 

<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/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>org.sonatype.mavenbook.simple</groupId>    <artifactId>simple</artifactId>    <packaging>jar</packaging>    <version>1.0-SNAPSHOT</version>    <name>simple</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>

This pom.xml file is the most basic POM you will ever deal with for a Maven project, usually a POM file is considerably more complex:defining multiple dependencies and customizing plugin behavior. The first few elements—groupId, artifactId, packaging, version—are what is known as the Maven coordinates which uniquely identify a project. name and url are descriptive elements of the POM providing a human readable name and associating the project with a web site. The dependencies element defines a single, test-scoped dependency on a unit testingframework called JUnit. These topics will be further introduced inSection 3.5, “Core Concepts”, all you need to know, at this point, is that the pom.xml is the file that makes Maven go.

Maven always executes against an effective POM(有效的POM,你定义的pom.xml文件可能很简单,但是maven会给它添加一些默认的配置,使用这个命令你就可以查看了), a combination(结合;组合;联合;[化学] 化合) of settings from this project’spom.xml, all parent POMs, a super-POM defined within Maven, user-defined settings, and active profiles. All projects ultimately(最后;根本;基本上) extend the super-POM, which defines a set of sensible default configuration settings. While your project might havea relatively minimal pom.xml, the contents of your project’s POM are interpolated with the contents of all parent POMs, user settings, and any active profiles. To see this "effective" POM, run the following command in the simple project’s base directory.

$ mvn help:effective-pom

When you run this, you should see a much larger POM which exposes the default settings of Maven. This goal can come in handy if you are trying to debug a build and want to see how all of the current project’s ancestor POMs are contributing to the effective POM.

<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>org.sonatype.mavenbook</groupId>  <artifactId>simple</artifactId>  <version>1.0-SNAPSHOT</version>  <name>simple</name>  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>  </dependencies>  <repositories>    <repository>      <snapshots>        <enabled>false</enabled>      </snapshots>      <id>central</id>      <name>Central Repository</name>      <url>https://repo.maven.apache.org/maven2</url>    </repository>  </repositories>  <pluginRepositories>    <pluginRepository>      <releases>        <updatePolicy>never</updatePolicy>      </releases>      <snapshots>        <enabled>false</enabled>      </snapshots>      <id>central</id>      <name>Central Repository</name>      <url>https://repo.maven.apache.org/maven2</url>    </pluginRepository>  </pluginRepositories>  <build>    <sourceDirectory>/Users/adamqiqi/maijunjin/maven/simple/src/main/java</sourceDirectory>    <scriptSourceDirectory>/Users/adamqiqi/maijunjin/maven/simple/src/main/scripts</scriptSourceDirectory>    <testSourceDirectory>/Users/adamqiqi/maijunjin/maven/simple/src/test/java</testSourceDirectory>    <outputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/classes</outputDirectory>    <testOutputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/test-classes</testOutputDirectory>    <resources>      <resource>        <directory>/Users/adamqiqi/maijunjin/maven/simple/src/main/resources</directory>      </resource>    </resources>    <testResources>      <testResource>        <directory>/Users/adamqiqi/maijunjin/maven/simple/src/test/resources</directory>      </testResource>    </testResources>    <directory>/Users/adamqiqi/maijunjin/maven/simple/target</directory>    <finalName>simple-1.0-SNAPSHOT</finalName>    <pluginManagement>      <plugins>        <plugin>          <artifactId>maven-antrun-plugin</artifactId>          <version>1.3</version>        </plugin>        <plugin>          <artifactId>maven-assembly-plugin</artifactId>          <version>2.2-beta-5</version>        </plugin>        <plugin>          <artifactId>maven-dependency-plugin</artifactId>          <version>2.8</version>        </plugin>        <plugin>          <artifactId>maven-release-plugin</artifactId>          <version>2.3.2</version>        </plugin>      </plugins>    </pluginManagement>    <plugins>      <plugin>        <artifactId>maven-clean-plugin</artifactId>        <version>2.5</version>        <executions>          <execution>            <id>default-clean</id>            <phase>clean</phase>            <goals>              <goal>clean</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-resources-plugin</artifactId>        <version>2.6</version>        <executions>          <execution>            <id>default-testResources</id>            <phase>process-test-resources</phase>            <goals>              <goal>testResources</goal>            </goals>          </execution>          <execution>            <id>default-resources</id>            <phase>process-resources</phase>            <goals>              <goal>resources</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-jar-plugin</artifactId>        <version>2.4</version>        <executions>          <execution>            <id>default-jar</id>            <phase>package</phase>            <goals>              <goal>jar</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-compiler-plugin</artifactId>        <version>3.1</version>        <executions>          <execution>            <id>default-compile</id>            <phase>compile</phase>            <goals>              <goal>compile</goal>            </goals>          </execution>          <execution>            <id>default-testCompile</id>            <phase>test-compile</phase>            <goals>              <goal>testCompile</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-surefire-plugin</artifactId>        <version>2.12.4</version>        <executions>          <execution>            <id>default-test</id>            <phase>test</phase>            <goals>              <goal>test</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-install-plugin</artifactId>        <version>2.4</version>        <executions>          <execution>            <id>default-install</id>            <phase>install</phase>            <goals>              <goal>install</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-deploy-plugin</artifactId>        <version>2.7</version>        <executions>          <execution>            <id>default-deploy</id>            <phase>deploy</phase>            <goals>              <goal>deploy</goal>            </goals>          </execution>        </executions>      </plugin>      <plugin>        <artifactId>maven-site-plugin</artifactId>        <version>3.3</version>        <executions>          <execution>            <id>default-site</id>            <phase>site</phase>            <goals>              <goal>site</goal>            </goals>            <configuration>              <outputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/site</outputDirectory>              <reportPlugins>                <reportPlugin>                  <groupId>org.apache.maven.plugins</groupId>                  <artifactId>maven-project-info-reports-plugin</artifactId>                </reportPlugin>              </reportPlugins>            </configuration>          </execution>          <execution>            <id>default-deploy</id>            <phase>site-deploy</phase>            <goals>              <goal>deploy</goal>            </goals>            <configuration>              <outputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/site</outputDirectory>              <reportPlugins>                <reportPlugin>                  <groupId>org.apache.maven.plugins</groupId>                  <artifactId>maven-project-info-reports-plugin</artifactId>                </reportPlugin>              </reportPlugins>            </configuration>          </execution>        </executions>        <configuration>          <outputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/site</outputDirectory>          <reportPlugins>            <reportPlugin>              <groupId>org.apache.maven.plugins</groupId>              <artifactId>maven-project-info-reports-plugin</artifactId>            </reportPlugin>          </reportPlugins>        </configuration>      </plugin>    </plugins>  </build>  <reporting>    <outputDirectory>/Users/adamqiqi/maijunjin/maven/simple/target/site</outputDirectory>  </reporting></project>



0 0