Maven的使用教程

这里不再说么maven的安装和环境变量配置

Maven基本命令及使用

前往项目pom.xml所在目录,或者直接使用Eclipse的m2e插件来操作。

mvn clean         清除上次打包的内容,在项目的target目录下

mvn test            测试,结合单元测试使用

mvn compile      编译,如果缺包,可以促使项目自己去下载引用包

mvn install         把项目安装到本地仓库,供其他项目试验

mvn package     打包,这里指打出jar包

mvn deploy        部署,将自己开发的项目打包部署到中央服务器,供其他人使用

mvn assembly:assembly 用插件归档打包

扫描二维码关注公众号,回复: 414504 查看本文章

maven的setting.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<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
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  -->
  <!--本地仓库。该值表示构建系统本地仓库的路径。其默认值为~/.m2/repository。 -->  
  <localRepository>F:\coding\apache-maven-3.2.5\.m2\repository</localRepository>


  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <!--配置服务端的一些设置。一些设置如安全证书不应该和pom.xml一起分发。这种类型的信息应该存在于构建服务器上的settings.xml文件中。--> 
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
	<!--这是server的id(注意不是用户登陆的id),该id与pom.xml中distributionManagement中repository元素的id相匹配。--> 
    <server>
      <id>user-snapshots</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
	
    <server>
      <id>user-release</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
	
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors> 
	    <!--给定仓库的下载镜像。 -->   
	<mirror> 
		    <!--该镜像的唯一标识符。id用来区分不同的mirror元素。 --> 
            <id>nexus</id> 
			<!--该镜像的URL。构建系统会优先考虑使用该URL,而非使用默认的服务器URL。 --> 
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url> 
			<!-- 这里只有配置正确,镜像才会同步远程jar包。-->
			<!-- 被镜像的服务器的id。例如,如果我们要设置了一个Maven中央仓库(http://repo1.maven.org/maven2)的镜像,就需要将该元素设置成central。这必须和中央仓库的id central完全一致。-->  
			<mirrorOf>central</mirrorOf>
        </mirror> 
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
<profiles>  
  <profile> 
    <id>public</id>
    <repositories>  
      <repository>  
	    <!--该配置的唯一标识符。 --> 
        <id>public</id>  
		<name>public</name>
        <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
        <releases>  
          <enabled>true</enabled>  
        </releases>  
        <snapshots>  
          <enabled>true</enabled>  
        </snapshots>  
      </repository>  
    </repositories>  
	
	 <pluginRepositories>  
        <pluginRepository>  
            <id>public</id>  
            <name>public</name>  
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </pluginRepository>  
    </pluginRepositories>
	
  </profile>  
</profiles>  

<activeProfiles>  
  <activeProfile>public</activeProfile>  
</activeProfiles> 

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

maven的项目配置(pom.xml中指定仓库,配置在<project>的下面),如果已经配置了Maven的Setting.xml,可以不用指定仓库

<repositories>  
        <repository>  
            <id>public</id>  
            <name>public</name>  
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </repository>  
    </repositories>  

   <pluginRepositories>  
        <pluginRepository>  
            <id>public</id>  
            <name>public</name>  
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </pluginRepository>  
    </pluginRepositories>

Maven项目引用包

<dependencies>  
	  <dependency>
	  	<groupId>net.sf.ehcache</groupId>
	  	<artifactId>ehcache-web</artifactId>
	  	<version>2.0.0</version>
	  </dependency>
   	  <dependency>  
     	<groupId>junit</groupId>  
     	<artifactId>junit</artifactId>  
     	<version>4.9</version>  
   	  </dependency>  
   	  <dependency>
  		<groupId>org.jsoup</groupId>
  		<artifactId>jsoup</artifactId>
  		<version>1.7.3</version>
	  </dependency>
	  <dependency>
  	  	<groupId>org.springframework</groupId>
  		<artifactId>spring-core</artifactId>
  		<version>3.0.5.RELEASE</version>
	  </dependency>
	  <dependency>
  		<groupId>c3p0</groupId>
  		<artifactId>c3p0</artifactId>
  		<version>0.9.1.2</version>
	  </dependency>
	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.38</version>
	</dependency>
 </dependencies> 

Maven打runable jar的build

<build>
		<finalName>hxtest</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<resources>
			<!-- 控制资源文件的拷贝 -->
			<resource>
				<directory>src/main/resources</directory>
				<targetPath>${project.build.directory}</targetPath>
			</resource>
		</resources>
		<plugins>
			<!-- 设置源文件编码方式 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<defaultLibBundleDir>lib</defaultLibBundleDir>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
							<mainClass>com.hiekn.test.HelloWorld</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- 拷贝依赖的jar包到lib目录 -->
			<plugin>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<attach>true</attach>
					<encoding>UTF-8</encoding>
				</configuration>
				<executions>
					<execution>
						<phase>compile</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
 </build>

Maven runable jar with 依赖包, 命令mvn assembly:assembly

 <build>  
    <plugins>  
        <plugin>  
            <artifactId>maven-assembly-plugin</artifactId>  
            <configuration>  
                <appendAssemblyId>false</appendAssemblyId>  
                <descriptorRefs>  
                    <descriptorRef>jar-with-dependencies</descriptorRef>  
                </descriptorRefs>  
                <archive>  
                    <manifest>  
                        <mainClass>com.hiekn.test.HelloWorld</mainClass>  
                    </manifest>  
                </archive>  
            </configuration>  
            <executions>  
                <execution>  
                    <id>make-assembly</id>  
                    <phase>package</phase>  
                    <goals>  
                        <goal>assembly</goal>  
                    </goals>  
                </execution>  
            </executions>  
        </plugin>  
    </plugins>  
</build>

  

Maven deploy配置,注意,需要和setting.xml里的sever保持相同id,以验证账号密码

<distributionManagement>  
        <repository>  
            <id>user-release</id>  
            <name>User Project Release</name>  
            <url>http://192.168.1.201:8081/nexus/content/repositories/releases/</url>  
        </repository>  
  
        <snapshotRepository>  
            <id>user-snapshots</id>  
            <name>User Project SNAPSHOTS</name>  
            <url>http://192.168.1.201:8081/nexus/content/repositories/snapshots/</url>  
        </snapshotRepository>  
</distributionManagement> 

maven的test,这里对应好路径,方法命名规则,能自动测试。

假设业务代码如下

package com.hiekn.test;

public class HelloWorld {
	
	public static void main(String args[]){
		HelloWorld h = new HelloWorld();
		System.out.print(h.say());
	}
	
	
	public String say(){
		return "hello world";
	}
	
}

对应测试代码

package com.hiekn.test;

import static org.junit.Assert.*;

import org.junit.Test;


public class HelloWorldTest{

	@Test
	public void testSay(){
		
		HelloWorld h = new HelloWorld();
		String s = h.say();
		assertEquals("hello world",s);
	
	}
}

下面是测试的一个比较全的pom.xml供参考

<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.hiekn</groupId>
  <artifactId>com.hiekn.test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>hx</name>
  <description>hxss</description>
  
    <!-- 
  <repositories>  
        <repository>  
            <id>public</id>  
            <name>public</name>  
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </repository>  
    </repositories>  

   <pluginRepositories>  
        <pluginRepository>  
            <id>public</id>  
            <name>public</name>  
            <url>http://192.168.1.201:8081/nexus/content/groups/public/</url>  
            <releases>  
                <enabled>true</enabled>  
            </releases>  
            <snapshots>  
                <enabled>true</enabled>  
            </snapshots>  
        </pluginRepository>  
    </pluginRepositories>
   -->
     
  <dependencies>  
	  <dependency>
	  	<groupId>net.sf.ehcache</groupId>
	  	<artifactId>ehcache-web</artifactId>
	  	<version>2.0.0</version>
	  </dependency>
   	  <dependency>  
     	<groupId>junit</groupId>  
     	<artifactId>junit</artifactId>  
     	<version>4.9</version>  
   	  </dependency>  
   	  <dependency>
  		<groupId>org.jsoup</groupId>
  		<artifactId>jsoup</artifactId>
  		<version>1.7.3</version>
	  </dependency>
	  <dependency>
  	  	<groupId>org.springframework</groupId>
  		<artifactId>spring-core</artifactId>
  		<version>3.0.5.RELEASE</version>
	  </dependency>
	  <dependency>
  		<groupId>c3p0</groupId>
  		<artifactId>c3p0</artifactId>
  		<version>0.9.1.2</version>
	  </dependency>
	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.38</version>
	</dependency>
 </dependencies> 
 
 
 <build>
		<finalName>hxtest</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<resources>
			<!-- 控制资源文件的拷贝 -->
			<resource>
				<directory>src/main/resources</directory>
				<targetPath>${project.build.directory}</targetPath>
			</resource>
		</resources>
		<plugins>
			<!-- 设置源文件编码方式 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<defaultLibBundleDir>lib</defaultLibBundleDir>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
							<mainClass>com.hiekn.test.HelloWorld</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- 拷贝依赖的jar包到lib目录 -->
			<plugin>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<attach>true</attach>
					<encoding>UTF-8</encoding>
				</configuration>
				<executions>
					<execution>
						<phase>compile</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
 </build>
 
 
 <distributionManagement>  
        <repository>  
            <id>user-release</id>  
            <name>User Project Release</name>  
            <url>http://192.168.1.201:8081/nexus/content/repositories/releases/</url>  
        </repository>  
  
        <snapshotRepository>  
            <id>user-snapshots</id>  
            <name>User Project SNAPSHOTS</name>  
            <url>http://192.168.1.201:8081/nexus/content/repositories/snapshots/</url>  
        </snapshotRepository>  
    </distributionManagement>  
 
</project>

 

猜你喜欢

转载自tcxiang.iteye.com/blog/2276592