版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010376788/article/details/56968353
在用Maven打包项目时,要像Hadoop、Spark、Hive等项目打包之后的文件包含bin、lib、conf之类的文件夹,同时可以动态的修改项目的配置参数,需要如下两步:
- 在 pom.xml 文件中引入 maven-assembly 插件;
- 在 assembly.xml 文件中制定各个文件目录。
pom.xml引入maven-assembly插件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>true</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>maven-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.1 http://maven.apache.org/xsd/assembly-1.1.1.xsd">
<id>all</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>bin</directory>
<outputDirectory>bin</outputDirectory>
<fileMode>755</fileMode>
</fileSet>
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory>conf</outputDirectory>
<fileMode>755</fileMode>
<lineEnding>unix</lineEnding>
<excludes>
<exclude>*.formatted</exclude>
</excludes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<fileMode>755</fileMode>
<outputDirectory>lib</outputDirectory>
<scope>runtime</scope>
<useProjectArtifact>false</useProjectArtifact>
<excludes>
<exclude>${project.groupId}:${project.artifactId}</exclude>
</excludes>
</dependencySet>
<dependencySet>
<fileMode>755</fileMode>
<outputFileNameMapping>${project.artifactId}.jar</outputFileNameMapping>
<outputDirectory>/lib/</outputDirectory>
<scope>runtime</scope>
<includes>
<include>${project.groupId}:${project.artifactId}</include>
</includes>
</dependencySet>
</dependencySets>
</assembly>
不难发现,我们把打好的程序jar包也放到了 lib目录 中。
执行代码
用这种方法打的jar包,是不包含依赖的jar包和配置文件的。所以,在执行之前需要把依赖的jar包和配置文件加入到 $CLASSPATH 中,Shell脚本如下:
#!/usr/bin/env bash
BIN=`dirname $0`
BIN=`cd $BIN; pwd`
APP_HOME=`dirname $BIN`
JAVA=${JAVA_HOME}/bin/java
CLASSPATH=${APP_HOME}/conf
#JAR=${APP_HOME}/tools.jar
for f in ${APP_HOME}/lib/*.jar; do
CLASSPATH=${CLASSPATH}:$f
done
for f in ${APP_HOME}/*.jar; do
CLASSPATH=${CLASSPATH}:$f
done
MAINCLASS="edu.wzm.joda.JodaDemo"
exec "$JAVA" -classpath $CLASSPATH $MAINCLASS