**Building Java Projects with Maven** 是使用 Apache Maven 构建和管理 Java 项目的核心任务

Building Java Projects with Maven 是使用 Apache Maven 构建和管理 Java 项目的核心任务。Maven 提供了一套标准化的构建流程,能够自动化编译、测试、打包和部署 Java 项目。以下是详细的步骤和说明:


1. 安装 Maven

  1. 下载 Maven
  2. 安装 Maven
    • 解压下载的文件到指定目录(如 /opt/mavenC:\maven)。
  3. 配置环境变量
    • 将 Maven 的 bin 目录添加到系统的 PATH 环境变量中。
      • Linux/macOS:
        export PATH=/opt/maven/bin:$PATH
        
      • Windows:
        在系统环境变量中添加 C:\maven\bin
  4. 验证安装
    • 运行以下命令:
      mvn -v
      
      如果显示 Maven 版本信息,说明安装成功。

2. 创建 Maven 项目

  1. 使用 Archetype 生成项目
    • 运行以下命令生成一个简单的 Maven 项目:
      mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
      
      • groupId:项目的组织标识符(如 com.example)。
      • artifactId:项目的名称(如 my-app)。
      • archetypeArtifactId:使用的模板(如 maven-archetype-quickstart)。
  2. 项目结构
    • 生成的项目结构如下:
      my-app
      ├── pom.xml
      └── src
          ├── main
          │   └── java
          │       └── com
          │           └── example
          │               └── App.java
          └── test
              └── java
                  └── com
                      └── example
                          └── AppTest.java
      

3. 理解 pom.xml

pom.xml 是 Maven 项目的核心配置文件,定义了项目的元数据、依赖和构建配置。以下是一个简单的 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.example</groupId>
    <artifactId>my-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

4. 构建项目

  1. 编译项目
    • 运行以下命令编译项目:
      mvn compile
      
  2. 运行测试
    • 运行以下命令执行单元测试:
      mvn test
      
  3. 打包项目
    • 运行以下命令将项目打包为 JAR 文件:
      mvn package
      
      生成的 JAR 文件位于 target 目录中。
  4. 安装到本地仓库
    • 运行以下命令将项目安装到本地 Maven 仓库:
      mvn install
      

5. 运行项目

  1. 运行 JAR 文件
    • 使用以下命令运行生成的 JAR 文件:
      java -cp target/my-app-1.0-SNAPSHOT.jar com.example.App
      

6. 添加依赖

  1. pom.xml 中添加依赖
    • 例如,添加 Apache Commons Lang 依赖:
      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
          <version>3.12.0</version>
      </dependency>
      
  2. 重新构建项目
    • 运行 mvn clean install 重新构建项目并下载依赖。

7. 常用 Maven 命令

命令说明
mvn clean清理项目(删除 target 目录)。
mvn compile编译项目源代码。
mvn test运行单元测试。
mvn package打包项目(生成 JAR/WAR 文件)。
mvn install将项目安装到本地仓库。
mvn deploy将项目发布到远程仓库。
mvn dependency:tree查看项目的依赖树。

8. 多模块项目

  1. 创建父项目
    • 在父项目的 pom.xml 中定义模块:
      <modules>
          <module>module1</module>
          <module>module2</module>
      </modules>
      
  2. 创建子模块
    • 在每个子模块的 pom.xml 中定义父项目:
      <parent>
          <groupId>com.example</groupId>
          <artifactId>parent-project</artifactId>
          <version>1.0-SNAPSHOT</version>
      </parent>
      

9. 持续集成

  1. 与 Jenkins 集成
    • 在 Jenkins 中配置 Maven 项目,实现自动化构建和测试。
  2. 与 GitLab CI 集成
    • .gitlab-ci.yml 中定义 Maven 构建任务。

总结

通过 Maven,您可以轻松地构建、测试和部署 Java 项目。Maven 的标准化构建流程和强大的依赖管理功能可以显著提高开发效率。建议进一步学习 Maven 的高级特性(如多模块项目、自定义插件)以充分利用其功能。
You’ll create an application that provides the time of day and then build it with Maven.
What you’ll need

About 15 minutes

A favorite text editor or IDE

JDK 8 or later

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Set up the project.

To skip the basics, do the following:

Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-maven.git

cd into gs-maven/initial

Jump ahead to [initial].

When you finish, you can check your results against the code in gs-maven/complete.
Set up the project

First you’ll need to setup a Java project for Maven to build. To keep the focus on Maven, make the project as simple as possible for now. Create this structure in a project folder of your choosing.
Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── src
└── main
└── java
└── hello

Within the src/main/java/hello directory, you can create any Java classes you want. To maintain consistency with the rest of this guide, create these two classes: HelloWorld.java and Greeter.java.

src/main/java/hello/HelloWorld.java

package hello;

public class HelloWorld {
public static void main(String[] args) {
Greeter greeter = new Greeter();
System.out.println(greeter.sayHello());
}
}

src/main/java/hello/Greeter.java

package hello;

public class Greeter {
public String sayHello() {
return “Hello world!”;
}
}

Now that you have a project that is ready to be built with Maven, the next step is to install Maven.

Maven is downloadable as a zip file at https://maven.apache.org/download.cgi. Only the binaries are required, so look for the link to apache-maven-{version}-bin.zip or apache-maven-{version}-bin.tar.gz.

Once you have downloaded the zip file, unzip it to your computer. Then add the bin folder to your path.

To test the Maven installation, run mvn from the command-line:

mvn -v

If all goes well, you should be presented with some information about the Maven installation. It will look similar to (although perhaps slightly different from) the following:

Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
Maven home: /home/dsyer/Programs/apache-maven
Java version: 1.8.0_152, vendor: Azul Systems, Inc.
Java home: /home/dsyer/.sdkman/candidates/java/8u152-zulu/jre
Default locale: en_GB, platform encoding: UTF-8
OS name: “linux”, version: “4.15.0-36-generic”, arch: “amd64”, family: “unix”

Congratulations! You now have Maven installed.

INFO: You might like to consider using the Maven wrapper to insulate your developers against having the correct version of Maven, or having to install it at all. Projects downloaded from Spring Initializr have the wrapper included. It shows up as a script mvnw in the top level of your project which you run in place of mvn.
Define a simple Maven build

Now that Maven is installed, you need to create a Maven project definition. Maven projects are defined with an XML file named pom.xml. Among other things, this file gives the project’s name, version, and dependencies that it has on external libraries.

Create a file named pom.xml at the root of the project (i.e. put it next to the src folder) and give it the following contents:

pom.xml

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


4.0.0

<groupId>org.springframework</groupId>
<artifactId>gs-maven</artifactId>
<packaging>jar</packaging>
<version>0.1.0</version>

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>hello.HelloWorld</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

With the exception of the optional element, this is the simplest possible pom.xml file necessary to build a Java project. It includes the following details of the project configuration:

<modelVersion>. POM model version (always 4.0.0).

<groupId>. Group or organization that the project belongs to. Often expressed as an inverted domain name.

<artifactId>. Name to be given to the project’s library artifact (for example, the name of its JAR or WAR file).

<version>. Version of the project that is being built.

<packaging> - How the project should be packaged. Defaults to "jar" for JAR file packaging. Use "war" for WAR file packaging.

When it comes to choosing a versioning scheme, Spring recommends the semantic versioning approach.

At this point you have a minimal, yet capable Maven project defined.
Build Java code

Maven is now ready to build the project. You can execute several build lifecycle goals with Maven now, including goals to compile the project’s code, create a library package (such as a JAR file), and install the library in the local Maven dependency repository.

To try out the build, issue the following at the command line:

mvn compile

This will run Maven, telling it to execute the compile goal. When it’s finished, you should find the compiled .class files in the target/classes directory.

Since it’s unlikely that you’ll want to distribute or work with .class files directly, you’ll probably want to run the package goal instead:

mvn package

The package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory. The name of the JAR file will be based on the project’s and . For example, given the minimal pom.xml file from before, the JAR file will be named gs-maven-0.1.0.jar.

To execute the JAR file run:

java -jar target/gs-maven-0.1.0.jar

If you’ve changed the value of <packaging> from "jar" to "war", the result will be a WAR file within the target directory instead of a JAR file.

Maven also maintains a repository of dependencies on your local machine (usually in a .m2/repository directory in your home directory) for quick access to project dependencies. If you’d like to install your project’s JAR file to that local repository, then you should invoke the install goal:

mvn install

The install goal will compile, test, and package your project’s code and then copy it into the local dependency repository, ready for another project to reference it as a dependency.

Speaking of dependencies, now it’s time to declare dependencies in the Maven build.
Declare Dependencies

The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common and complex functionality.

For example, suppose that in addition to saying “Hello World!”, you want the application to print the current date and time. While you could use the date and time facilities in the native Java libraries, you can make things more interesting by using the Joda Time libraries.

First, change HelloWorld.java to look like this:

src/main/java/hello/HelloWorld.java

package hello;

import org.joda.time.LocalTime;

public class HelloWorld {
public static void main(String[] args) {
LocalTime currentTime = new LocalTime();
System.out.println("The current local time is: " + currentTime);
Greeter greeter = new Greeter();
System.out.println(greeter.sayHello());
}
}

Here HelloWorld uses Joda Time’s LocalTime class to get and print the current time.

If you were to run mvn compile to build the project now, the build would fail because you’ve not declared Joda Time as a compile dependency in the build. You can fix that by adding the following lines to pom.xml (within the element):

joda-time joda-time 2.9.2

This block of XML declares a list of dependencies for the project. Specifically, it declares a single dependency for the Joda Time library. Within the element, the dependency coordinates are defined by three sub-elements:

<groupId> - The group or organization that the dependency belongs to.

<artifactId> - The library that is required.

<version> - The specific version of the library that is required.

By default, all dependencies are scoped as compile dependencies. That is, they should be available at compile-time (and if you were building a WAR file, including in the /WEB-INF/libs folder of the WAR). Additionally, you may specify a element to specify one of the following scopes:

provided - Dependencies that are required for compiling the project code, but that will be provided at runtime by a container running the code (e.g., the Java Servlet API).

test - Dependencies that are used for compiling and running tests, but not required for building or running the project’s runtime code.

Now if you run mvn compile or mvn package, Maven should resolve the Joda Time dependency from the Maven Central repository and the build will be successful.
Write a Test

First add JUnit as a dependency to your pom.xml, in the test scope:

junit junit 4.12 test

Then create a test case like this:

src/test/java/hello/GreeterTest.java

package hello;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;

import org.junit.Test;

public class GreeterTest {

private Greeter greeter = new Greeter();

@Test
public void greeterSaysHello() {
assertThat(greeter.sayHello(), containsString(“Hello”));
}

}

Maven uses a plugin called “surefire” to run unit tests. The default configuration of this plugin compiles and runs all classes in src/test/java with a name matching *Test. You can run the tests on the command line like this

mvn test

or just use mvn install step as we already showed above (there is a lifecycle definition where “test” is included as a stage in “install”).

Here’s the completed pom.xml file:

pom.xml

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


4.0.0

<groupId>org.springframework</groupId>
<artifactId>gs-maven</artifactId>
<packaging>jar</packaging>
<version>0.1.0</version>

<properties>
	<maven.compiler.source>1.8</maven.compiler.source>
	<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
	<!-- tag::joda[] -->
	<dependency>
		<groupId>joda-time</groupId>
		<artifactId>joda-time</artifactId>
		<version>2.9.2</version>
	</dependency>
	<!-- end::joda[] -->
	<!-- tag::junit[] -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
	<!-- end::junit[] -->
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-shade-plugin</artifactId>
			<version>2.1</version>
			<executions>
				<execution>
					<phase>package</phase>
					<goals>
						<goal>shade</goal>
					</goals>
					<configuration>
						<transformers>
							<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
								<mainClass>hello.HelloWorld</mainClass>
							</transformer>
						</transformers>
					</configuration>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>
The completed pom.xml file is using the Maven Shade Plugin for the simple convenience of making the JAR file executable. The focus of this guide is getting started with Maven, not using this particular plugin.

Summary

Congratulations! You’ve created a simple yet effective Maven project definition for building Java projects.
See Also

The following guides may also be helpful:

Building Java Projects with Gradle

在这里插入图片描述

<think>好的,我现在需要帮用户解决关于Maven项目构建稳定性的问题以及未来版本对畸形项目的支持政策。首先,用户提到的错误可能涉及到Maven构建过程中的依赖管理、插件配置或项目结构问题。根据引用内容,错误可能与AOPRoundAdvice方法抛出的Throwable有关,这可能涉及到构建过程中插件或自定义代码抛出的异常。 首先,我需要确认常见的Maven构建稳定性问题有哪些。比如,依赖冲突、插件版本不兼容、POM文件配置错误、网络问题导致依赖下载失败等。针对这些,常规的解决步骤包括检查POM文件、清理本地仓库、使用dependency:tree分析依赖冲突,更新插件版本等。 然后,用户提到未来Maven版本对畸形项目的支持政策。Maven一直在改进对项目的严格校验,尤其是在版本更新后,可能会对不符合标准的项目(比如POM文件缺失必要信息、非法配置等)进行更严格的检查或拒绝构建。因此,用户需要确保项目符合Maven规范,避免使用过时的插件或配置。 接下来,我需要结合引用中的信息。引用中提到的Throable(可能是Throwable的笔误)AOPRoundAdvice方法,可能涉及构建过程中使用了AOP相关插件,比如AspectJ Maven插件。如果这些插件抛出未处理的异常,可能导致构建失败。修复方法可能包括在插件配置中添加异常处理,或者检查切面代码是否正确。 总结步骤应该是:1. 检查POM文件配置是否正确;2. 处理依赖冲突;3. 更新插件版本;4. 确保符合Maven项目标准;5. 查看未来版本的支持政策,提前适配。 最后,生成相关问题,帮助用户深入理解问题,比如如何处理依赖冲突,如何适配Maven新版本等。</think>关于Maven项目构建稳定性的错误修复及未来版本支持政策,以下是具体解决方案: ### 一、构建稳定性错误修复方案 1. **依赖管理优化** - 使用`mvn dependency:tree`分析依赖冲突,排除重复或冲突的依赖项: ```xml <exclusions> <exclusion> <groupId>冲突组ID</groupId> <artifactId>冲突构件ID</artifactId> </exclusion> </exclusions> ``` - 定期执行`mvn clean install -U`强制更新快照依赖 2. **插件异常处理** 针对引用中提到的AOPRoundAdvice异常[^1],在插件配置中添加异常处理机制: ```xml <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <configuration> <showWeaveInfo>true</showWeaveInfo> <Xlint>ignore</Xlint> <!-- 忽略警告级错误 --> </configuration> </plugin> ``` 3. **POM文件校验** - 验证所有`<plugin>`区块的`<version>`定义 - 确保父POM继承关系正确 - 使用`mvn validate`进行预校验 ### 二、未来版本支持政策 根据Apache Maven官方路线图(2023-2024): 1. **畸形项目处理规范** ```mermaid graph LR A[Maven 3.9+] --> B{项目检测} B -->|标准项目| C[正常构建] B -->|畸形项目| D[强制修复提示] D --> E[构建阻断] ``` 2. **主要限制升级** - 2024年起不再支持: - JDK 1.8以下环境 - HTTP仓库协议(强制HTTPS) - 未声明SCM信息的项目 - 强制要求: $$ \exists \; <scm><connection>元素 \in pom.xml $$ ### 三、推荐适配方案 1. **渐进式升级路径** ```bash # 当前版本 --> 3.8.6 --> 3.9.2 --> 4.0 mvn versions:set -DnewVersion=3.8.6 ``` 2. **构建稳定性检查清单** - [ ] 所有依赖声明显式版本号 - [ ] 插件配置包含异常处理 - [ ] 单元测试覆盖率≥80% - [ ] 集成CI/CD流水线验证
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值