利用maven打包Java项目为可执行jar
前言
maven作为目前最为流行的项目构建工具,对于创建大型的协作Java项目有很好的支持作用。那么如何利用maven创建一个引用了第三方jar包的可执行项目呢?本文详细介绍相关流程。
方法步骤
1、下载maven并进行配置
进入apache maven官网的下载仓库:https://archive.apache.org/dist/maven/maven-3/3.5.4/binaries/
下载maven3.5.4,下载完成后解压缩至目标路径,并将其中的bin目录配置到环境变量–PATH当中。
2、使用IDEA创建MAVEN项目
IDEA自带maven项目构建工具,因此可以直接创建maven项目,打开IDEA软件新建Project,在Project类型当中选择maven,此时勾选“自模板中创建项目”,并选择apache-maven-quikstart作为项目模板。
3、编写项目代码
本项目需求是将消费者信息打印到一个excel表格中,由于本文重点在于部署项目,因此具体实现仅附方法代码,如下:
public static void processExcel(ArrayList<? extends Customer> arraylist){
HSSFWorkbook hssfworkbook=new HSSFWorkbook();
Sheet worksheet=hssfworkbook.createSheet("First");
List<String> a= Arrays.asList("customer_id","customer_name","customer_birthday","customer_phonenum","customer_bill");
HashMap<String,String> value=new HashMap<>();
Row row=worksheet.createRow(0);
int index=0;
for(int i=0;i<a.size();i++){
row.createCell(i).setCellValue(a.get(index));
// index++;
}
int index_row=1;
for(Customer c:arraylist) {
// int c_size=c.getClass().getDeclaredFields().length;
Row row_content=worksheet.createRow(index_row);
row_content.createCell(0).setCellValue(c.getCustomer_id());
row_content.createCell(1).setCellValue(c.getCustomer_name());
row_content.createCell(2).setCellValue(c.getCustomer_birthday());
row_content.createCell(3).setCellValue(c.getCustomer_phonenum());
row_content.createCell(4).setCellValue(c.getCustomer_bill());
index_row++;
}
try {
File f=new File("../workbook.xls");
if(!f.exists())
f.createNewFile();
hssfworkbook.write(f);
}
catch(Exception e){
System.out.println("The file does not exists");
}
}
4、部署maven项目
(1)修改pom文档,在jar插件下添加manifest配置
默认的package调用jar插件,其中是不包括manifest文件信息的。这样打包出的jar没有mainclass也就无法直接运行,因此我们使用如下配置,将主类和依赖路径同时添加到jar插件中,方便package语句调用
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<mainClass>主类全类名</mainClass>
<addClasspath>true</addClasspath>
<ClasspathPrefix>dependency/</ClasspathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
(2)使用mvn clean dependency:copy-dependencies package命令将项目打包为可执行jar
进入项目pom文件所在目录。运行mvn clean dependency:copy-dependencies package 指令,即可在target目录下得到jar文件。进入target目录,使用java -jar jar包名即可运行。
注意
mvn中的dependency:copy-dependencies 指令默认会将依赖拷贝到target/dependency文件夹下,因此在配置打包参数时,选择的ClasspathPrefix参数设置为dependency。