基于Maven编写命令行应用:最佳实践

java命令行应用 =
一些*.jar文件   + 
*.sh可执行脚本

如果你的应用是基于maven的, 可以参考以下实践,避免走弯路。

以下所有资料从网上汇集而来

使用assembly插件将jar和可执行脚本打包成 *.zip


<!--pom.xml-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<descriptors>
						<descriptor>src/main/assembly/assembly.xml</descriptor>
					</descriptors>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

<!--src/main/assembly/assembly.xml -->
<!--jar文件将打在zipFile/jars目录下 -->
<!--脚本文件可以src/main/bin下,打包后在zipFile/bin目录下-->
<assembly>
	<id>jarset</id>
	<formats>
		<format>zip</format>
	</formats>
	<includeBaseDirectory>true</includeBaseDirectory>
	<fileSets>
		<fileSet>
			<directory>src/main/bin</directory>
			<outputDirectory>/bin</outputDirectory>
			<fileMode>755</fileMode>
			<directoryMode>755</directoryMode>
		</fileSet>
	</fileSets>
	<dependencySets>
		<dependencySet>
			<outputDirectory>/jars</outputDirectory>
			<scope>runtime</scope>
		</dependencySet>
	</dependencySets>
</assembly> 

编写*nix下的shell文件

#这里的关键是要把jars/*.jar加入classpath,可以这样写
#!/bin/sh

PRG="$0"  
  
# resolve links - $0 may be a softlink  
while [ -h "$PRG" ]; do  
  ls=`ls -ld "$PRG"`  
  link=`expr "$ls" : '.*-> \(.*\)$'`  
  if expr "$link" : '/.*' > /dev/null; then  
    PRG="$link"  
  else  
    PRG=`dirname "$PRG"`/"$link"  
  fi  
done  
  
  
PRGDIR=`dirname "$PRG"`  
PRGDIR_PARENT=`cd "$PRGDIR/.." >/dev/null; pwd`


java -cp $(echo $PRGDIR_PARENT/jars/*.jar | tr ' ' ':') somepackage.SomeClass $*

(可选)使用timestamp作为程序的版本号

频繁变更、不太严谨的命令行应用可以使用timestamp作为程序的版本号

<!--pom.xml-->
	<groupId>some.group</groupId>
	<artifactId>some.artifact</artifactId>
	<version>${maven.build.timestamp}</version>
	<properties>
		<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
	</properties>

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.