1. 程式人生 > >如何在Maven中構建SWT應用並打包成可執行的jar包

如何在Maven中構建SWT應用並打包成可執行的jar包

    前面在Maven中構建SWT應用的時候發現SWT相關jar包在Maven中央倉庫上找不到,後面在stackoverflow上有人提供了一個倉庫地址:https://github.com/maven-eclipse/maven-eclipse.github.io

    根據上面所說,SWT相關依賴在Maven中央倉庫中不可取,目前存在的Maven倉庫不包括所有平臺的包,也沒有原始碼和debug包,總之就是沒有提供可信賴和自動化的方式更新和倉庫再生,而http://maven-eclipse.github.io/maven這個倉庫會自動下載並打包官方的SWT釋出版本。

 

一、如何新增swt相關依賴

在pom.xml中新增下面的倉庫地址:

<repositories>
	<repository>
		<id>maven-eclipse-repo</id>
		<url>http://maven-eclipse.github.io/maven</url>
	</repository>
</repositories>

下面是各平臺的依賴:

<dependencies>
	<dependency>
		<groupId>org.eclipse.swt</groupId>
		<artifactId>org.eclipse.swt.win32.win32.x86</artifactId>
		<version>${swt.version}</version>
		<!-- To use the debug jar, add this -->
		<classifier>debug</classifier>
	</dependency>
	<dependency>
		<groupId>org.eclipse.swt</groupId>
		<artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
		<version>${swt.version}</version>
	</dependency>
	<dependency>
		<groupId>org.eclipse.swt</groupId>
		<artifactId>org.eclipse.swt.gtk.linux.x86</artifactId>
		<version>${swt.version}</version>
	</dependency>
	<dependency>
		<groupId>org.eclipse.swt</groupId>
		<artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>
		<version>${swt.version}</version>
	</dependency>
	<dependency>
		<groupId>org.eclipse.swt</groupId>
		<artifactId>org.eclipse.swt.cocoa.macosx.x86_64</artifactId>
		<version>${swt.version}</version>
	</dependency>
</dependencies>

二、如何通過Maven打包成可執行的jar並打包依賴

這裡要用到maven-assembly-plugin外掛而不是maven-jar-plugin,maven-jar-plugin並不會打包依賴,而通過maven-assembly-plugin可以打包依賴、元件、文件和其它檔案到jar中,具體參考Maven官網關於assembly外掛的介紹:https://maven.apache.org/plugins/maven-assembly-plugin

在pom.xml中新增assembly外掛:

<build>
    <finalName>${project.name}</finalName>
	<plugins>
		<plugin>
			<!-- 這裡不需要指定groupId,預設為org.apache.maven.plugins -->
			<artifactId>maven-assembly-plugin</artifactId>
			<version>3.1.0</version>
			<configuration>
				<archive>
					<manifest>
						<addClasspath>true</addClasspath>
						<mainClass>com.iboxpay.ui.MainWindow</mainClass>
					</manifest>
				</archive>
				<descriptorRefs>
					<descriptorRef>jar-with-dependencies</descriptorRef>
				</descriptorRefs>
			</configuration>
			<executions>
				<execution>
					<id>make-assembly</id> <!-- this is used for inheritance merges -->
					<phase>package</phase> <!-- bind to the packaging phase -->
					<goals>
						<goal>single</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

注意:

<descriptorRef>jar-with-dependencies</descriptorRef>標籤中的內容必須為jar-with-dependencies,否則打包時會出錯,若想自定義配置描述符,參考https://maven.apache.org/plugins/maven-assembly-plugin/usage.html

配完後執行maven package會生成連個包,一個通過maven-jar-plugin打包生成的"工程名.jar",另一個是通過maven-assembly-plugin打包生成的"工程名-jar-with-dependencies.jar"。後者可通過java -jar  工程名-jar-with-dependencies.jar 直接執行。