Maven配置不同平台下的SWT依赖

通常在pom.xml里我们可以像对其他类库一样为项目引入SWT依赖:

<dependency>
 <groupId>org.eclipse.swt</groupId>
 <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
 <version>4.3</version>
</dependency>

但是SWT特殊在于,不同平台(platform)下需要使用不同的artifactId,例如上面的代码只适用于windows开发环境,在linux环境下可以编译但无法运行。

好在Maven支持根据os.family定义不同的属性值,所以我们可以像下面这样定义两个profile,然后让Maven自动选择合适的artifactId:

<profiles>
 <profile>
 <id>os_linux</id>
 <activation>
 <os>
 <family>unix</family>
 </os>
 </activation>
 <properties>
 <swt-artifactId>org.eclipse.swt.gtk.linux.x86_64</swt-artifactId>
 </properties>
 </profile>
 <profile>
 <id>os_windows</id>
 <activation>
 <os>
 <family>windows</family>
 </os>
 </activation>
 <properties>
 <swt-artifactId>org.eclipse.swt.win32.win32.x86_64</swt-artifactId>
 </properties>
 </profile>
</profiles>

<dependency>
 <groupId>org.eclipse.swt</groupId>
 <artifactId>${swt-artifactId}</artifactId>
 <version>4.3</version>
</dependency>

参考链接: