maven简单使用
- 安装配置JAVA环境
- 下载安装maven (http://maven.apache.org/),配置环境变量M2_HOME,配置环境变量M2_HOME)3. 生成项目骨架: mvn archetype:generate -DgroupId=com.lx.app -DartifactId=helloworld
- 创建HelloWorld.java
package com.lx.app; /** * Hello world! * */ public class HelloWorld { public static void main( String[] args ) { System.out.println(new HelloWorld().sayHello()); } public String sayHello(){ return "HelloWorld"; } }
- 编译
mvn clean compile
- 创建 HelloWorldTest.java
package com.lx.app; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HelloWorldTest { @Test public void testSayHello() { HelloWorld helloWorld = new HelloWorld(); String result = helloWorld.sayHello(); assertEquals("HelloWorld", result); } }
- 测试HelloWorld (这里不需要引入HelloWorld 他们属于同一层级)
mvn clean test
- 打包 (默认会打成jar包)
mvn clean package
- 安装到本地库(打包后只有安装到本地库, 其他的模块才可以引用他)
mvn install
- 生成可执行jar包 修改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.lx.app</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>helloworld</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>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<!-- 打包带有主函数入口的jar包 -->
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.lx.app.HelloWorld</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
- maven中央仓库
最佳实践
- artifacid maven自动生成的项目目录以artifactid开头, 所以这里推荐以 项目-模块起名
ps: 后续如果有干货继续补充。
网友评论