如何发布Maven构建的项目?代码举例讲解

发布Maven构建的项目主要有以下几个步骤:

  1. 在pom.xml中配置groupId、artifactId和version,这三个元素唯一标识一个Maven项目:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>myproject</artifactId>
  <version>1.0</version> 
</project>
  1. 在中配置项目打包方式,如jar、war等:
<build>
    <finalName>myproject</finalName> 
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>  
    </plugins>
</build> 
  1. 在中配置release仓库和snapshot仓库:
<distributionManagement>  
    <repository>  
        <id>nexus-releases</id>  
        <url>http://.../nexus/content/repositories/releases</url>  
    </repository>  
    <snapshotRepository>  
        <id>nexus-snapshots</id>  
        <url>http://.../nexus/content/repositories/snapshots</url>  
    </snapshotRepository>
</distributionManagement>
  1. 在部署过程中填写用户名和密码:
mvn deploy  -DaltDeploymentRepository=internal.repo::default::http://.../nexus/content/repositories/releases 
    -DaltSnapshotDeploymentRepository=internal.repo::default::http://.../nexus/content/repositories/snapshots
    -Dnexus.user=username -Dnexus.password=password
  1. 部署release版本使用mvn deploy,部署snapshot版本使用mvn deploy。
    来看一个简单示例:
    pom.xml配置:
<project>  
    <modelVersion>4.0.0</modelVersion>  
    <groupId>com.example</groupId>  
    <artifactId>myproject</artifactId>  
    <version>1.0</version>

    <build>  
        ... 
    </build>  

    <distributionManagement>  
        <repository>  
            <id>nexus-releases</id>  
            <url>http://.../nexus/content/repositories/releases</url>  
        </repository>  
        <snapshotRepository>  
            <id>nexus-snapshots</id>  
            <url>http://.../nexus/content/repositories/snapshots</url>  
        </snapshotRepository>
    </distributionManagement>
</project> 

命令:

mvn deploy -DaltDeploymentRepository=internal.repo::default::http://.../nexus/content/repositories/releases 
-DaltSnapshotDeploymentRepository=internal.repo::default::http://.../nexus/content/repositories/snapshots
-Dnexus.user=username -Dnexus.password=password

所以,通过配置相关信息,我们可以将Maven构建的项目部署到远程仓库,供其他人使用。